Boost/Perl Regex Look behind containing OR
Boost/Perl Regex Look behind containing OR
我正在尝试使用后视来检查前面的元素是 space 还是字符串开头:
(?<=^|\s)
这在 regex101
上工作正常,风格设置为 PHP
,但在 boost
(我认为是 Perl
)下会出现语法错误。我认为是 ^
导致了这个问题。我找不到任何关于为什么会这样的文档,因此非常感谢您的见解。
您应该能够在 boost 的后视中使用 |
,但每个备选方案必须具有相同(固定)长度的限制。
^
是一个断言,因此长度为 0
\s
正好匹配一个字符,所以它的长度是1。
PCRE 放宽了这个限制:每个备选方案仍然必须是固定长度,但它们现在不一定需要等长。
这是 PCRE docs 中的相关行:
(a) Although lookbehind assertions in PCRE2 must match fixed length strings, each alternative branch of a lookbehind assertion can match a different length of string. Perl requires them all to have the same length.
事实上,如果您尝试,Perl 将输出以下错误:
$ perl -e 'm#(?<=^|\s)#'
Variable length lookbehind not implemented in regex m/(?<=^|\s)/ at -e line 1.
现在,关于解决方案,您需要找到解决方法。我将在这里引用 :
As an aside a good workaround can be (?<!\S)
that handles the two cases. For more complex cases, nothing forbids to write (?:(?<=sub1)|(?<=sub2)|...)
我正在尝试使用后视来检查前面的元素是 space 还是字符串开头:
(?<=^|\s)
这在 regex101
上工作正常,风格设置为 PHP
,但在 boost
(我认为是 Perl
)下会出现语法错误。我认为是 ^
导致了这个问题。我找不到任何关于为什么会这样的文档,因此非常感谢您的见解。
您应该能够在 boost 的后视中使用 |
,但每个备选方案必须具有相同(固定)长度的限制。
^
是一个断言,因此长度为 0\s
正好匹配一个字符,所以它的长度是1。
PCRE 放宽了这个限制:每个备选方案仍然必须是固定长度,但它们现在不一定需要等长。
这是 PCRE docs 中的相关行:
(a) Although lookbehind assertions in PCRE2 must match fixed length strings, each alternative branch of a lookbehind assertion can match a different length of string. Perl requires them all to have the same length.
事实上,如果您尝试,Perl 将输出以下错误:
$ perl -e 'm#(?<=^|\s)#' Variable length lookbehind not implemented in regex m/(?<=^|\s)/ at -e line 1.
现在,关于解决方案,您需要找到解决方法。我将在这里引用
As an aside a good workaround can be
(?<!\S)
that handles the two cases. For more complex cases, nothing forbids to write(?:(?<=sub1)|(?<=sub2)|...)