更新时间:2023-02-26 14:02:20
go
的 regexp
包不支持零宽度环顾.您可以使用 regexp.FindAllStringSubmatch()
函数利用捕获的分组:
go
's regexp
package does not support zero width lookarounds. You can leverage captured grouping with the regexp.FindAllStringSubmatch()
function:
package main
import (
"regexp"
"fmt"
)
func main() {
str := "foo(bar)foo(baz)golang"
rex := regexp.MustCompile(`\(([^)]+)\)`)
out := rex.FindAllStringSubmatch(str, -1)
for _, i := range out {
fmt.Println(i[1])
}
}
输出:
bar
baz
正则表达式 \(([[^)] +)\)
:
\(
匹配文字(
([[^)] +)
匹配子字符串直到下一个)
并将匹配项放入捕获的组中,在这里您可以使用非贪婪匹配.*?\)
([^)]+)
matches substring upto next )
and put the match in a captured group, here you can use non-greeedy match .*?\)
too
\)
匹配文字)