2 回答
TA贡献2019条经验 获得超9个赞
使用正则表达式。QuoteMeta 在搜索字符串中引用元字符。
pattern := fmt.Sprintf(`(%s)`, regexp.QuoteMeta(searchString))
pat := regexp.MustCompile("(?i)" + pattern)
content = pat.ReplaceAllString(content, replacementString)
TA贡献1757条经验 获得超8个赞
package main
import (
"fmt"
"regexp"
)
type rep struct {
from string
to string
}
func replace(str string, reps []rep) (result string) {
result = str
for i := range reps {
rx := regexp.MustCompile(fmt.Sprintf("(?i)(%s)", regexp.QuoteMeta(reps[i].from)))
result = rx.ReplaceAllString(result, reps[i].to)
}
return
}
func main() {
content := `
{
"key_1": "SoME_SEArCH_STRING",
"key_2": "some_some_SEARCH_STRING_string",
"key_3": ["SOME_SEARCH_STRING"],
"key_4": "aBc"
}`
var replaces = []rep{
{`["SOME_SEARCH_STRING"]`, `["INTv2RPACS"]`},// important: array replacements before strings
{`SOME_SEARCH_STRING`, `REPLACEMENT_STRING`},
}
fmt.Println(content)
fmt.Println(replace(content, replaces))
}
output:
{
"key_1": "SoME_SEArCH_STRING",
"key_2": "some_some_SEARCH_STRING_string",
"key_3": ["SOME_SEARCH_STRING"],
"key_4": "aBc"
}
{
"key_1": "REPLACEMENT_STRING",
"key_2": "some_REPLACEMENT_STRING_string",
"key_3": ["INTv2RPACS"],
"key_4": "aBc"
}
- 2 回答
- 0 关注
- 80 浏览
添加回答
举报