在 re2 中使用正前瞻 (?=regex)
Using positive-lookahead (?=regex) with re2
因为我对 re2, I'm trying to figure out how to use positive-lookahead (?=regex)
like JS, C++ or any PCRE style in Go 有点陌生。
这里有一些我正在寻找的例子。
JS:
'foo bar baz'.match(/^[\s\S]+?(?=baz|$)/);
Python:
re.match('^[\s\S]+?(?=baz|$)', 'foo bar baz')
- 注意:两个示例都匹配
'foo bar '
非常感谢。
您可以使用更简单的正则表达式实现此目的:
re := regexp.MustCompile(`^(.+?)(?:baz)?$`)
sm := re.FindStringSubmatch("foo bar baz")
fmt.Printf("%q\n", sm)
sm[1]
将是您的对手。游乐场:http://play.golang.org/p/Vyah7cfBlH
根据 Syntax Documentation,不支持此功能:
(?=re)
before text matching re
(NOT SUPPORTED)
此外,来自 WhyRE2:
As a matter of principle, RE2 does not support constructs for which only backtracking solutions are known to exist. Thus, backreferences and look-around assertions are not supported.
因为我对 re2, I'm trying to figure out how to use positive-lookahead (?=regex)
like JS, C++ or any PCRE style in Go 有点陌生。
这里有一些我正在寻找的例子。
JS:
'foo bar baz'.match(/^[\s\S]+?(?=baz|$)/);
Python:
re.match('^[\s\S]+?(?=baz|$)', 'foo bar baz')
- 注意:两个示例都匹配
'foo bar '
非常感谢。
您可以使用更简单的正则表达式实现此目的:
re := regexp.MustCompile(`^(.+?)(?:baz)?$`)
sm := re.FindStringSubmatch("foo bar baz")
fmt.Printf("%q\n", sm)
sm[1]
将是您的对手。游乐场:http://play.golang.org/p/Vyah7cfBlH
根据 Syntax Documentation,不支持此功能:
(?=re)
before text matchingre
(NOT SUPPORTED)
此外,来自 WhyRE2:
As a matter of principle, RE2 does not support constructs for which only backtracking solutions are known to exist. Thus, backreferences and look-around assertions are not supported.