正向后发断言(Positive Lookbehind)

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

语法

(?<=...)

示例

(?<=foo)bar

匹配 bar,仅当其前面有 foo 时匹配,但 foo 不包含在匹配结果中。

解释:

  • 在字符串 foobar 中,(?<=foo)bar 会匹配 bar,因为 bar 前面有 foo。
  • 在字符串 quxbar 中,(?<=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']