虽然使用 regexp 通常会产生一个优雅而紧凑的解决方案,但它通常不是最快的。

strings.Replacer

Replacer 用替换项替换字符串列表。多个 goroutines 并发使用是安全的。

strings.NewReplacer()Replacer.Replace()

它看起来像这样:

const replacement = "<br>\n"


var replacer = strings.NewReplacer(

    "\r\n", replacement,

    "\r", replacement,

    "\n", replacement,

    "\v", replacement,

    "\f", replacement,

    "\u0085", replacement,

    "\u2028", replacement,

    "\u2029", replacement,

)


func replaceReplacer(s string) string {

    return replacer.Replace(s)

}

以下是Wiktor 答案中的正则表达式解决方案:


var re = regexp.MustCompile(`\r\n|[\r\n\v\f\x{0085}\x{2028}\x{2029}]`)


func replaceRegexp(s string) string {

    return re.ReplaceAllString(s, "<br>\n")

}

实施实际上相当快。这是一个简单的基准测试,将其与上述预编译的正则表达式解决方案进行比较:


const input = "1st\nsecond\r\nthird\r4th\u0085fifth\u2028sixth"


func BenchmarkReplacer(b *testing.B) {

    for i := 0; i < b.N; i++ {

        replaceReplacer(input)

    }

}


func BenchmarkRegexp(b *testing.B) {

    for i := 0; i < b.N; i++ {

        replaceRegexp(input)

    }

}

基准测试结果:


BenchmarkReplacer-4      3000000               495 ns/op

BenchmarkRegexp-4         500000              2787 ns/op

strings.Replacer
stringstringio.Writerstringstrings.ReplacerReplacer.WriteString()io.Writerstring