這個問題在這里已經有了答案: 在 Golang 中使用替換的正則運算式 1 個答案 5 小時前關閉。
我想替換字串:
"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 )]`)
非常感謝!
uj5u.com熱心網友回復:
如果您有一個 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 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/429783.html
