我发现其他一些语言支持连续匹配锚点\G
\G锚点指定必须在上一次匹配结束的点上进行匹配。
但我发现\G在Golang regex中是一个无效的标记。等价物是什么?
发布于 2020-08-15 20:20:32
似乎不支持\G
。package docs状态:
所接受的正则表达式的语法与Perl、Python和其他语言使用的通用语法相同。更准确地说,它是被RE2接受并在https://golang.org/s/re2syntax中描述的语法,\C除外。
在RE2中,除了Perl之外,\G
是明确不受支持的:
\G at end of last match (NOT SUPPORTED) PERL
在Regexp
类型的方法中,没有任何强制连续匹配的方法。如果您一定要实现此结果,则很可能必须编写自定义代码。
Hacky演示代码:
package main
import (
"fmt"
"regexp"
"strings"
)
const s = "foo,bar,baz,qu!ux,foox"
func main() {
re, err := regexp.Compile(`\w+,?`)
if err != nil {
panic(err)
}
matches := re.FindAllString(s, -1)
var (
split int
curidx int
)
for _, m := range matches {
if strings.Index(s, m) != curidx {
break
}
curidx += len(m)
split++
}
contiguousMatches := matches[:split]
fmt.Println(contiguousMatches) // [foo, bar, baz, qu]
}
https://stackoverflow.com/questions/63429549
复制