Go

时间:2015-07-10 19:33:06

标签: string replace go

NewReplacer.Replace可以执行不区分大小写的字符串替换吗?

r := strings.NewReplacer("html", "xml")
fmt.Println(r.Replace("This is <b>HTML</b>!"))

如果没有,在Go中使用不区分大小写的字符串替换的最佳方法是什么?

3 个答案:

答案 0 :(得分:8)

您可以使用正则表达式:

re := regexp.MustCompile(`(?i)html`)
fmt.Println(re.ReplaceAllString("html HTML Html", "XML"))

游乐场:http://play.golang.org/p/H0Gk6pbp2c

值得注意的是,根据语言和语言环境,案例可能会有所不同。例如,德语字母“ß”的大写形式是“SS”。虽然这通常不会影响英语文本,但在处理需要使用它们的多语言文本和程序时,需要牢记这一点。

答案 1 :(得分:2)

根据文档does not

我不确定最好的方法,但您可以使用replace in regular expressions执行此操作,并使用i flag

使其不区分大小写

答案 2 :(得分:1)

通用解决方案如下:

import (
    "fmt"
    "regexp"
)

type CaseInsensitiveReplacer struct {
    toReplace   *regexp.Regexp
    replaceWith string
}

func NewCaseInsensitiveReplacer(toReplace, replaceWith string) *CaseInsensitiveReplacer {
    return &CaseInsensitiveReplacer{
        toReplace:   regexp.MustCompile("(?i)" + toReplace),
        replaceWith: replaceWith,
    }
}

func (cir *CaseInsensitiveReplacer) Replace(str string) string {
    return cir.toReplace.ReplaceAllString(str, cir.replaceWith)
}

然后通过:

使用
r := NewCaseInsensitiveReplacer("html", "xml")
fmt.Println(r.Replace("This is <b>HTML</b>!"))

这里是游乐场中的link示例。