我想用正则表达式而不是全部替换一个实例。我将如何使用 Go 的regexp
库来做到这一点?
输入:foobar1xfoobar2x
正则表达式:bar(.)x
替换:baz$1
ReplaceAllString
输出:foobaz1foobaz2
ReplaceOneString
输出:foobaz1foobar2x
一般来说,如果你使用惰性匹配并使用锚点作为开始和结束,你可以有替换优先行为:
replace `^(.*?)bar(.*)$` with `$1baz$2`.
例子:
package main
import (
"fmt"
"regexp"
)
func main() {
src := "foobar1xfoobar2x"
pat := regexp.MustCompile("^(.*?)bar(.*)$")
repl := "${1}baz$2"
output := pat.ReplaceAllString(src, repl)
fmt.Println(output)
}
输出
foobaz1xfoobar2x
I had the same problem. The most clean solution I've come up with:
package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
re, _ := regexp.Compile("[a-z]{3}")
s := "aaa bbb ccc"
// Replace all strings
fmt.Println(re.ReplaceAllString(s, "000"))
// Replace one string
found := re.FindString(s)
if found != "" {
fmt.Println(strings.Replace(s, found, "000", 1))
}
}
Running:
$ go run test.go
000 000 000
000 bbb ccc
我无法使用公认的解决方案,因为我的模式非常复杂。我最终使用了 ReplaceAllStringFunc : https: //play.golang.org/p/ihtuIU-WEYG
package main
import (
"fmt"
"regexp"
)
var pat = regexp.MustCompile("bar(.)(x)")
func main() {
src := "foobar1xfoobar2x"
flag := false
output := pat.ReplaceAllStringFunc(src, func(a string) string {
if flag {
return a
}
flag = true
return pat.ReplaceAllString(a, "baz$1$2")
})
fmt.Println(output)
}