【发布时间】:2015-07-11 04:08:26
【问题描述】:
NewReplacer.Replace 可以做不区分大小写的字符串替换吗?
r := strings.NewReplacer("html", "xml")
fmt.Println(r.Replace("This is <b>HTML</b>!"))
如果不是,在 Go 中进行不区分大小写的字符串替换的最佳方法是什么?
【问题讨论】:
NewReplacer.Replace 可以做不区分大小写的字符串替换吗?
r := strings.NewReplacer("html", "xml")
fmt.Println(r.Replace("This is <b>HTML</b>!"))
如果不是,在 Go 中进行不区分大小写的字符串替换的最佳方法是什么?
【问题讨论】:
您可以为此使用正则表达式:
re := regexp.MustCompile(`(?i)html`)
fmt.Println(re.ReplaceAllString("html HTML Html", "XML"))
游乐场:http://play.golang.org/p/H0Gk6pbp2c.
值得注意的是,大小写可能会因语言和区域设置而异。例如,德语字母“ß”的大写形式是“SS”。虽然这通常不会影响英文文本,但在处理多语言文本和需要处理它们的程序时,请牢记这一点。
【讨论】:
一个通用的解决方案如下:
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 到操场上的一个例子。
【讨论】:
基于does not 的文档。
我不确定最好的方法,但您可以使用 replace in regular expressions 执行此操作,并使用 i flag 使其不区分大小写
【讨论】: