Golang如何替换正则表达式组中的字符串?

我想替换字符串:

"hello [Jim], I'm [Sam]""hello [MR Jim], I'm [MR Sam]"

"[Greetings] hello [Jim], I'm [Sam]""[Greetings] hello [MR Jim], I'm [MR Sam]"

我怎样才能通过 golang 正则表达式做到这一点?

re := regexp.MustCompile(`hello [(\w+)], I'm [(\w+)]`)

非常感谢!


慕标琳琳
浏览 202回答 1
1回答

慕哥9229398

如果您有一个 para 需要从中识别字符串,那么您可能可以使用两个正则表达式来实现它:namePattern := `\[(\w+)\]`replacerRegex := regexp.MustCompile(namePattern)finderRegex := regexp.MustCompile("hello " + namePattern + ", I'm " + namePattern)fmt.Println(re.ReplaceAllString(re1.FindString("hi hih hi hello [Jim], I'm [Sam]"), "[MR $1]"))https://go.dev/play/p/kv6CfTv0-sk编辑:保留字符串其他部分的简单方法(PS:可以优化并需要检查边缘情况)str := "pre string hello [Jim], I'm [Sam] post string"namePattern := `\[(\w+)\]`finderRegex := regexp.MustCompile("hello " + namePattern + ", I'm " + namePattern)replacerRegex := regexp.MustCompile(namePattern)// string part subject to replacementstr_rep := finderRegex.FindString(str)// array of string holding the pre and post part ( check for str_rep as it could be empty)strPart := strings.Split(str, str_rep)replaced_str := replacerRegex.ReplaceAllString(str_rep, "[MR $1]")// concat to get the final string (implement checks for edge cases)finalStr := strPart[0] + replaced_str + strPart[1]fmt.Println(finalStr)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go