本文整理汇总了Golang中strings.Replace函数的典型用法代码示例。如果您正苦于以下问题:Golang Replace函数的具体用法?Golang Replace怎么用?Golang Replace使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Replace函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: escape_text
// A few CVEs contain characters that break Jira's text formatting
func escape_text(s string) string {
result := strings.Replace(s, "[", "\\[", -1)
result = strings.Replace(result, "]", "\\]", -1)
result = strings.Replace(result, "~", "\\~", -1)
return result
}
示例2: InitLog
// path can be ""
func InitLog(path string, debug bool) {
config := `
<seelog type="sync" minlevel="${minlevel}">
<outputs formatid="main">
<console/>
<!-- ${extra} -->
</outputs>
<formats>
<format id="main" format="[EQ-%LEV] %Date(15:04:05.00): %Msg (at %File:%Line) %n"/>
</formats>
</seelog>`
if path != "" {
extra := fmt.Sprintf("<file path=\"%s\"/>", path)
config = strings.Replace(config, "<!-- ${extra} -->",
extra, -1)
}
Debug = debug
if debug {
config = strings.Replace(config, "${minlevel}", "debug", -1)
} else {
config = strings.Replace(config, "${minlevel}", "info", -1)
}
logger, err := seelog.LoggerFromConfigAsBytes([]byte(config))
if err != nil {
panic(err)
}
seelog.ReplaceLogger(logger)
if path != "" {
seelog.Debugf("Initialized the logger for %s", path)
}
}
示例3: Run
func (c *JoinCommand) Run(v *View, e *Edit) error {
sel := v.Sel()
for i := 0; i < sel.Len(); i++ {
r := sel.Get(i)
// Removing new line and triming in the selection
t := v.Buffer().Substr(r)
t = strings.Replace(t, "\r", "\n", -1)
slice := strings.Split(t, "\n")
t = ""
for j, s := range slice {
if j == 0 {
t += s
continue
}
t += " " + strings.TrimLeft(s, " \t")
}
v.Replace(e, r, t)
// Removing the first new line after selection
liner := v.Buffer().FullLine(r.End())
line := v.Buffer().Substr(liner)
line = strings.Replace(line, "\n", "", -1)
line = strings.Replace(line, "\r", "", -1)
line = strings.TrimRight(line, " \t")
// Triming the line after
nextline := liner.End() + 1
nextliner := v.Buffer().FullLine(nextline)
nline := v.Buffer().Substr(nextliner)
if nline != "" {
v.Replace(e, nextliner, " "+strings.TrimLeft(nline, " \t"))
}
v.Replace(e, liner, line)
}
return nil
}
示例4: isTeamCreationAllowed
func isTeamCreationAllowed(c *Context, email string) bool {
email = strings.ToLower(email)
if !utils.Cfg.TeamSettings.EnableTeamCreation && !HasPermissionToContext(c, model.PERMISSION_MANAGE_SYSTEM) {
c.Err = model.NewLocAppError("isTeamCreationAllowed", "api.team.is_team_creation_allowed.disabled.app_error", nil, "")
return false
}
if result := <-Srv.Store.User().GetByEmail(email); result.Err == nil {
user := result.Data.(*model.User)
if len(user.AuthService) > 0 && len(*user.AuthData) > 0 {
return true
}
}
// commas and @ signs are optional
// can be in the form of "@corp.mattermost.com, mattermost.com mattermost.org" -> corp.mattermost.com mattermost.com mattermost.org
domains := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(utils.Cfg.TeamSettings.RestrictCreationToDomains, "@", " ", -1), ",", " ", -1))))
matched := false
for _, d := range domains {
if strings.HasSuffix(email, "@"+d) {
matched = true
break
}
}
if len(utils.Cfg.TeamSettings.RestrictCreationToDomains) > 0 && !matched {
c.Err = model.NewLocAppError("isTeamCreationAllowed", "api.team.is_team_creation_allowed.domain.app_error", nil, "")
return false
}
return true
}
示例5: NewFileLogger
func NewFileLogger(gzipEnabled bool, compressionLevel int, filenameFormat, topic string) (*FileLogger, error) {
if gzipEnabled && strings.Index(filenameFormat, "<GZIPREV>") == -1 {
return nil, errors.New("missing <GZIPREV> in filenameFormat")
}
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
shortHostname := strings.Split(hostname, ".")[0]
identifier := shortHostname
if len(*hostIdentifier) != 0 {
identifier = strings.Replace(*hostIdentifier, "<SHORT_HOST>", shortHostname, -1)
identifier = strings.Replace(identifier, "<HOSTNAME>", hostname, -1)
}
filenameFormat = strings.Replace(filenameFormat, "<TOPIC>", topic, -1)
filenameFormat = strings.Replace(filenameFormat, "<HOST>", identifier, -1)
if gzipEnabled && !strings.HasSuffix(filenameFormat, ".gz") {
filenameFormat = filenameFormat + ".gz"
}
f := &FileLogger{
logChan: make(chan *Message, 1),
compressionLevel: compressionLevel,
filenameFormat: filenameFormat,
gzipEnabled: gzipEnabled,
ExitChan: make(chan int),
termChan: make(chan bool),
hupChan: make(chan bool),
}
return f, nil
}
示例6: parseHost
func parseHost(str string) (*Host, error) {
host := &Host{
Addr: str,
Port: "22",
}
if str != "" && str[0] == '[' {
i := strings.LastIndex(str, ":")
if i == -1 || i-1 < 1 {
return nil, fmt.Errorf("knownhosts: Invalid host: %#v", str)
}
host.Addr = str[1 : i-1]
host.Port = str[i+1:]
} else if strings.ContainsAny(str, "*?") {
pattern := str
if pattern[0] == '!' {
pattern = pattern[1:]
host.PatternNegated = true
}
pattern = strings.Replace(pattern, ".", "\\.", -1)
pattern = strings.Replace(pattern, "*", ".*", -1)
pattern = strings.Replace(pattern, "?", ".", -1)
r, err := regexp.Compile("^" + pattern + "$")
if err != nil {
return nil, err
}
host.Addr = ""
host.Pattern = r
host.PatternRaw = str
}
return host, nil
}
示例7: GetSubDomain
func GetSubDomain(s string) (string, string) {
s = strings.Replace(s, "http://", "", 1)
s = strings.Replace(s, "https://", "", 1)
match := wwwStart.MatchString(s)
if match {
return "", ""
}
match = betaStart.MatchString(s)
if match {
return "", ""
}
match = ciStart.MatchString(s)
if match {
return "", ""
}
parts := strings.Split(s, ".")
if len(parts) != 3 {
return "", ""
}
return parts[0], parts[1]
}
示例8: VersionPackage
// VersionPackage computes a given version package name.
// v1 => v1, V1 => v1, 1 => v1, 1.0 => v1 if unique - v1dot0 otherwise.
func VersionPackage(version string) string {
var others []string
design.Design.IterateVersions(func(v *design.APIVersionDefinition) error {
others = append(others, v.Version)
return nil
})
idx := strings.Index(version, ".")
if idx == 0 {
// weird but OK
version = strings.Replace(version, ".", "dot", -1)
} else if idx > 0 {
uniqueMajor := true
match := majorRegex.FindStringSubmatch(version)
if len(match) > 1 {
major := match[1]
for _, o := range others {
match = majorRegex.FindStringSubmatch(o)
if len(match) > 1 && major != match[1] {
uniqueMajor = false
break
}
}
}
if uniqueMajor {
version = version[:idx]
} else {
strings.Replace(version, ".", "dot", -1)
}
}
if digitPrefixRegex.MatchString(version) {
version = "v" + version
}
return Goify(version, false)
}
示例9: ProcessRename
func ProcessRename(page *Page, args []string) {
if len(args) < 1 {
errhandle(fmt.Errorf("'rename' rule needs an argument"))
}
dest := args[0]
if strings.Contains(dest, "*") {
if !strings.Contains(page.Pattern, "*") {
errhandle(fmt.Errorf(
"'rename' rule cannot rename '%s' to '%s'",
page.Pattern, dest))
}
group := fmt.Sprintf("([^%c]*)", filepath.Separator)
base := filepath.Base(page.Pattern)
pat := strings.Replace(regexp.QuoteMeta(base), "\\*", group, 1)
re, err := regexp.Compile(pat)
errhandle(err)
m := re.FindStringSubmatch(filepath.Base(page.Path))
dest = strings.Replace(dest, "*", m[1], 1)
}
page.Path = filepath.Join(filepath.Dir(page.Path), dest)
}
示例10: moveGitFiles
func moveGitFiles(src, dest string, errLog io.Writer) error {
cmd := exec.Command("git", "ls-files")
cmd.Dir = dest
cmd.Stderr = errLog
out, err := cmd.Output()
if err != nil {
return err
}
tracked := make(map[string]bool)
for _, filename := range strings.Split(string(out), "\n") {
if strings.TrimSpace(filename) == "" {
continue
}
tracked[filename] = true
}
return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return os.MkdirAll(strings.Replace(path, src, dest, 1), info.Mode())
}
if !info.Mode().IsRegular() {
return nil
}
relative := strings.Replace(path, src+"/", "", 1)
if !tracked[relative] {
return nil
}
return os.Rename(path, dest+"/"+relative)
})
}
示例11: WriteEdge
// Write one edge
func (rw *RefWriter) WriteEdge(from, to key.Key, linkname string) error {
if rw.Ctx != nil {
select {
case <-rw.Ctx.Done(): // just in case.
return rw.Ctx.Err()
default:
}
}
var s string
switch {
case rw.PrintFmt != "":
s = rw.PrintFmt
s = strings.Replace(s, "<src>", from.Pretty(), -1)
s = strings.Replace(s, "<dst>", to.Pretty(), -1)
s = strings.Replace(s, "<linkname>", linkname, -1)
case rw.PrintEdge:
s = from.Pretty() + " -> " + to.Pretty()
default:
s += to.Pretty()
}
rw.out <- &RefWrapper{Ref: s}
return nil
}
示例12: winPath
// winPath converts a path into a windows safe path
func winPath(s string) string {
s = strings.Replace(s, "?", "_", -1)
s = strings.Replace(s, `"`, "_", -1)
s = strings.Replace(s, "<", "_", -1)
s = strings.Replace(s, ">", "_", -1)
return s
}
示例13: CleanTeamName
func CleanTeamName(s string) string {
s = strings.ToLower(strings.Replace(s, " ", "-", -1))
for _, value := range reservedName {
if strings.Index(s, value) == 0 {
s = strings.Replace(s, value, "", -1)
}
}
s = strings.TrimSpace(s)
for _, c := range s {
char := fmt.Sprintf("%c", c)
if !validTeamNameCharacter.MatchString(char) {
s = strings.Replace(s, char, "", -1)
}
}
s = strings.Trim(s, "-")
if !IsValidTeamName(s) {
s = NewId()
}
return s
}
示例14: parse
func parse(s string) ([]string, error) {
if s == "" {
return nil, nil
}
if s[0] != Separator {
return nil, ErrInvalidPointer
}
prev := 0
tokens := []string{}
for i := 1; i < len(s); i++ {
switch s[i] {
case Separator:
tokens = append(tokens, s[prev+1:i])
prev = i
}
}
if prev != len(s) {
tokens = append(tokens, s[prev+1:])
}
dtokens := make([]string, 0, len(tokens))
for _, t := range tokens {
t = strings.Replace(strings.Replace(t, EncodedSlash, "/", -1), EncodedTilde, "~", -1)
dtokens = append(dtokens, t)
}
return dtokens, nil
}
示例15: isTreamCreationAllowed
func isTreamCreationAllowed(c *Context, email string) bool {
email = strings.ToLower(email)
if utils.Cfg.TeamSettings.DisableTeamCreation {
c.Err = model.NewAppError("isTreamCreationAllowed", "Team creation has been disabled. Please ask your systems administrator for details.", "")
return false
}
// commas and @ signs are optional
// can be in the form of "@corp.mattermost.com, mattermost.com mattermost.org" -> corp.mattermost.com mattermost.com mattermost.org
domains := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(utils.Cfg.TeamSettings.RestrictCreationToDomains, "@", " ", -1), ",", " ", -1))))
matched := false
for _, d := range domains {
if strings.HasSuffix(email, "@"+d) {
matched = true
break
}
}
if len(utils.Cfg.TeamSettings.RestrictCreationToDomains) > 0 && !matched {
c.Err = model.NewAppError("isTreamCreationAllowed", "Email must be from a specific domain (e.g. @example.com). Please ask your systems administrator for details.", "")
return false
}
return true
}