反向预查(Negative Lookahead)

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

语法

(?!...)

示例

foo(?!bar)

匹配 foo,仅当其后不跟 bar 时匹配。

解释:

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

应用场景

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

代码示例

Python

import re

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

JavaScript

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