Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

golang正则表达式如何成对匹配并且替换

如题,想要达成效果如下
原字符串 [内容] (xxxx)
结果字符串 http://xxxx/内容

原字符串中可能存在多个符合 []()格式的信息,希望能够全部替换掉


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
package main

import (
    "regexp"
    "fmt"
)

func main() {
    var re = regexp.MustCompile(`(?m)[([^[]]+)]s*(([^()]+))`)
    var str = `[内容] (xxxx)`
    var substitution = "http://$2/$1"
    
    fmt.Println(re.ReplaceAllString(str, substitution))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...