反向后发断言(Negative Lookbehind)

2024-06-24 18:47:38 278
反向后发断言是一种零宽度断言,用于在当前位置的左边检查某个子模式是否不存在,但该子模式不包含在最终匹配结果中。

语法

(?<!...)

示例

(?<!foo)bar

匹配 bar,仅当其前面没有 foo 时匹配。

解释:

  • 在字符串 quxbar 中,(?<!foo)bar 会匹配 bar,因为 bar 前面不是 foo。
  • 在字符串 foobar 中,(?<!foo)bar 不会匹配 bar,因为 bar 前面是 foo。

应用场景

  • 检查某个单词前面是否不跟特定的字符或字符串。
  • 排除不符合条件的模式。

代码示例

Python

import re

pattern = r'(?<!foo)bar'
test_string = 'foobar quxbar'
matches = re.findall(pattern, test_string)
print(matches)  # ['bar']

JavaScript

const pattern = /(?<!foo)bar/g;
const testString = 'foobar quxbar';
const matches = testString.match(pattern);
console.log(matches);  // ['bar']