2015-07-10 104 views
3

Can NewReplacer.Replace不区分大小写的字符串替换吗?不区分大小写的字符串替换Go

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

如果不是这样,那么在Go中执行不区分大小写的字符串替换的最佳方法是什么?

回答

8

您可以使用正则表达式为:

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

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

值得一提的是,case是一种可以根据语言和语言环境而不同的东西。例如,德语字母“ß”的大写形式是“SS”。虽然这通常不影响英文文本,但在处理需要使用它们的多语言文本和程序时,需要记住这一点。

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在游乐场的例子。

相关问题