文章

前瞻,负前瞻,后顾,负后顾

在 JavaScript 中,正则表达式中的前瞻(Lookahead)、后顾(Lookbehind)、负前瞻(Negative Lookahead)、负后顾(Negative Lookbehind)是一些高级的模式匹配概念,用于在不消费字符的情况下进行匹配。这些概念可以帮助你编写更强大和灵活的正则表达式。下面是每个概念的详细解释:

1.前瞻(Lookahead)

前瞻用于检查某个模式的后面是否紧跟着另一个特定的模式,但不包含在最终的匹配结果中。前瞻的语法是(?=…)。

示例: 匹配以 abc 开头,后面紧跟着 def 的字符串,但不包括 def 在结果中。

1
2
3
4
let regex = /abc(?=def)/;
let str = "abcdef";
let match = str.match(regex);
console.log(match[0]); // 输出 "abc"

2.负前瞻(Negative Lookahead)

负前瞻用于检查某个模式的后面是否不紧跟着另一个特定的模式,但不包含在最终的匹配结果中。负前瞻的语法是(?!…)。

示例: 匹配以 abc 开头,但后面不紧跟着 def 的字符串。

1
2
3
4
5
let regex = /abc(?!def)/;
let str1 = "abcxyz";
let str2 = "abcdef";
console.log(str1.match(regex)); // 输出 "abc"
console.log(str2.match(regex)); // 输出 null

3.后顾(Lookbehind)

后顾用于检查某个模式的前面是否紧跟着另一个特定的模式,但不包含在最终的匹配结果中。后顾的语法是(?<=…)。

示例: 匹配前面紧跟着 abc 的 def 字符串,但不包括 abc 在结果中。

1
2
3
4
let regex = /(?<=abc)def/;
let str = "abcdef";
let match = str.match(regex);
console.log(match[0]); // 输出 "def"

4.负后顾(Negative Lookbehind)

负后顾用于检查某个模式的前面是否不紧跟着另一个特定的模式,但不包含在最终的匹配结果中。负后顾的语法是(?<!…)。

示例: 匹配前面不紧跟着 abc 的 def 字符串。

1
2
3
4
5
let regex = /(?<!abc)def/;
let str1 = "xyzdef";
let str2 = "abcdef";
console.log(str1.match(regex)); // 输出 "def"
console.log(str2.match(regex)); // 输出 null

综合示例 假设我们有一个字符串 “123abc456def789”,我们想要匹配 456,但前提是它后面紧跟着 def,并且前面没有 abc。

1
2
3
4
5
6
7
let regex = /(?<!abc)456(?=def)/;
let str = "123abc456def789";
let match = str.match(regex);
console.log(match); // 输出 null,因为前面有 "abc"
let str2 = "123456def789";
let match2 = str2.match(regex);
console.log(match2[0]); // 输出 "456",因为前面没有 "abc" 且后面有 "def"

通过这些概念,你可以构建更精确和复杂的匹配模式,处理更复杂的字符串匹配需求。

本文由作者按照 CC BY 4.0 进行授权