星五博客

invalid or unsupported Perl syntax: `(?<`

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

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