golang的正则表达式库是个半成品,不支持复杂正则和预查等功能,可以使用三方优化的库regexp2,安装:

go get -u github.com/dlclark/regexp2

使用:大致上与regexp相同

m, _ := regexp2.MustCompile(`(?<=aaa).*?(?=ccc)`, 0).FindStringMatch("aaabbbccc")
fmt.Println(m.String())

regexp与regexp2差异:

Category

regexp regexp2
Catastrophic backtracking possible no, constant execution time guarantees yes, if your pattern is at risk you can use the re.MatchTimeout field
Python-style capture groups (?P<name>re) yes no (yes in RE2 compat mode)
.NET-style capture groups (?<name>re) or (?'name're) no yes
comments (?#comment) no yes
branch numbering reset (?|a|b) no no
possessive match (?>re) no yes
positive lookahead (?=re) no yes
negative lookahead (?!re) no yes
positive lookbehind (?<=re) no yes
negative lookbehind (?<!re) no yes
back reference \1 no yes
named back reference \k'name' no yes
named ascii character class [[:foo:]] yes no (yes in RE2 compat mode)
conditionals (?(expr)yes|no) no yes