让负面回顾与可选值一起工作的最有效方法是什么?

What is the most efficient way to get a negative lookbehind to work alongisde an optional value?

我知道负向后视必须为零宽度,但我注意到一个问题,如果前面的标记是可选的,它们将不起作用。为什么会这样?

(?<!test):?(\d{3})

test123 失败。 但是通过 test:123

除了 (?<!test|test:) 之外,还有其他解决方案吗?我宁愿避免上述解决方案,因为我想将其应用到的正则表达式已经有很多负面的后视短语,我会加倍。

编辑:我最初是使用 PCRE 编辑器发布的,但我正在使用 ICU

进行编码

使用 ICU 正则表达式引擎,您可以访问 constrained-width 回顾,允许在内部使用 已知长度 的限制量词回顾。

所以,使用

(?<!test:{0,1})\d{3}
        ^^^^^^

:{0,1} 将匹配一个或零 :

注意 ICU regex does not work the same as PCRE, you should be aware of the differences when testing in an incompatible environment, such as regex101.com.

ICU 中缺少的一些很酷的 PCRE 功能:

  • (*SKIP)(*FAIL) 动词
  • \K 运算符

PCRE 中缺少一些很酷的 ICU 功能:

  • 约束后视宽度((?<!test:{0,1})\d{3}
  • 字符class交集([\p{Letter}&&\p{script=cyrillic}])或相减([\p{Letter}--\p{script=latin}]