Go中不区分大小写的字符串替换

9
新的替换器(NewReplacer)能否进行不区分大小写的字符串替换?
r := strings.NewReplacer("html", "xml")
fmt.Println(r.Replace("This is <b>HTML</b>!"))

如果不行,那么在 Go 语言中实现不区分大小写的字符串替换有哪些最佳方法?
4个回答

14

你可以使用正则表达式来实现:

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

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

值得注意的是,大小写是一种可以因语言和区域而异的东西。例如,德语字母“ß”的大写形式是“SS”。虽然这通常不会影响英文文本,但在处理多语言文本和需要处理它们的程序时,这是需要记住的事情。


2

一个通用的解决方案如下:

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>!"))

这是一个在playground上的示例链接

1

根据文档,它这样做。

我不确定最好的方法是什么,但您可以使用正则表达式替换来执行此操作,并使用i标志使其不区分大小写。


1
func IReplace函数用于替换子字符串,不区分大小写。
使用正则表达式(如前面的帖子中提到的)并不适用于所有情况。例如:对于参数:("Alpha=? BETA", "ALPHA=?", ALPHA=1),结果应该是"ALPHA=1 BETA",但实际上并不是这样。
import (
    "strings"
    "unicode/utf8"
)

    func IReplace(s, old, new string) string {  // replace all, case insensitive
        if old == new || old == "" {
            return s // avoid allocation
        }
        t := strings.ToLower(s)
        o := strings.ToLower(old)
    
        // Compute number of replacements.
        n := strings.Count(t, o)
        if n == 0 {
            return s // avoid allocation
        }
        // Apply replacements to buffer.
        var b strings.Builder
        b.Grow(len(s) + n*(len(new)-len(old)))
        start := 0
        for i := 0; i < n; i++ {
            j := start
            if len(old) == 0 {
                if i > 0 {
                    _, wid := utf8.DecodeRuneInString(s[start:])
                    j += wid
                }
            } else {
                j += strings.Index(t[start:], o)
            }
            b.WriteString(s[start:j])
            b.WriteString(new)
            start = j + len(old)
        }
        b.WriteString(s[start:])
        return b.String()
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接