亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang如何替換正則表達式組中的字符串?

Golang如何替換正則表達式組中的字符串?

Go
慕標琳琳 2022-11-08 17:11:26
我想替換字符串:"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+)]`)非常感謝!
查看完整描述

1 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

如果您有一個 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)


查看完整回答
反對 回復 2022-11-08
  • 1 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號