英文:
Golang how to replace string in regex group?
问题
我想要替换字符串:
"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+)]`)
非常感谢!
英文:
I want to replace strings:
"hello [Jim], I'm [Sam]"
to "hello [MR Jim], I'm [MR Sam]"
"[Greetings] hello [Jim], I'm [Sam]"
to "[Greetings] hello [MR Jim], I'm [MR Sam]"
How can I do this via golang regex?
re := regexp.MustCompile(`hello [(\w+)], I'm [(\w+)]`)
Thank you very much!
答案1
得分: 0
如果你有一个段落,需要识别其中的字符串,你可以使用两个正则表达式来实现:
namePattern := `\[(\w+)\]`
replacerRegex := regexp.MustCompile(namePattern)
finderRegex := regexp.MustCompile("hello " + namePattern + ", I'm " + namePattern)
fmt.Println(replacerRegex.ReplaceAllString(finderRegex.FindString("hi hih hi hello [Jim], I'm [Sam]"), "[MR $1]"))
简单的方法来保留字符串的其他部分(注意:可以进行优化,并且需要检查边界情况):
str := "pre string hello [Jim], I'm [Sam] post string"
namePattern := `\[(\w+)\]`
finderRegex := regexp.MustCompile("hello " + namePattern + ", I'm " + namePattern)
replacerRegex := regexp.MustCompile(namePattern)
// 需要替换的字符串部分
str_rep := finderRegex.FindString(str)
// 字符串分割为前后两部分(注意检查 str_rep 是否为空)
strPart := strings.Split(str, str_rep)
replaced_str := replacerRegex.ReplaceAllString(str_rep, "[MR $1]")
// 拼接得到最终字符串(实现边界情况的检查)
finalStr := strPart[0] + replaced_str + strPart[1]
fmt.Println(finalStr)
你可以在这里运行代码:https://go.dev/play/p/kv6CfTv0-sk
英文:
If you have a para from which you need to identify the string then may be you could use two regex to achieve it:
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
EDIT:
simple way to retain other part of string (PS: can be optimized and need checks for edge cases)
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 replacement
str_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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论