2 回答
TA贡献1784条经验 获得超2个赞
您可以使用字符串文字(带反引号)来包含单引号和捕获组:
re := regexp.MustCompile(`(?s)bus'.\s+(.*?nuts)`)
看这个例子:
var source_txt = `bus driver drove steady although the bus's steering was going nuts.`
func main() {
fmt.Printf("Experiment with regular expressions.\n")
fmt.Printf("source text:\n")
fmt.Println("--------------------------------")
fmt.Printf("%s\n", source_txt)
fmt.Println("--------------------------------")
// a regular expression
regex := regexp.MustCompile(`(?s)bus'.\s+(.*?nuts)`)
fmt.Printf("regex: '%v'\n", regex)
matches := regex.FindStringSubmatch(source_txt)
for i, v := range matches {
fmt.Printf("match %2d: '%s'\n", i+1, v)
}
}
输出:
Experiment with regular expressions.
source text:
--------------------------------
bus driver drove steady although the bus's steering was going nuts.
--------------------------------
regex: '(?s)bus'.\s+(.*?nuts)'
match 1: 'bus's steering was going nuts'
match 2: 'steering was going nuts'
的FindStringSubmatch():
识别 s 中正则表达式最左边的匹配项及其子表达式的匹配项(如果有)
这match[1]将是第一个捕获组。
TA贡献1858条经验 获得超8个赞
我的搜索的正确答案应该是"steering was going nuts"......
如果您希望该子字符串作为您的匹配结果,您应该相应地调整您的正则表达式。
re := regexp.MustCompile("(?s)bus's (.*?nuts)")
rm := re.FindStringSubmatch(str)
if len(rm) != 0 {
fmt.Printf("%q\n", rm[0]) // "bus's steering was going nuts"
fmt.Printf("%q", rm[1]) // "steering was going nuts"
}
- 2 回答
- 0 关注
- 243 浏览
添加回答
举报