Golang how to replace string in regex group?

huangapple go评论77阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2022年2月21日 15:30:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/71202611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定