我正在浏览器的控制台中尝试下面的regex /(?<=.*)(\w\w)(?=.*)/。
我读了这个正则表达式如下:“查找和捕获任何两个字母数字字符之前和后面的零或更多的任何字符出现”。
与“ab de”作为输入,我希望我的浏览器匹配"ab","bc","cd“和"de”。
为什么它只给我"ab“和"cd"?
有没有办法让正则表达式返回我想要的所有匹配("ab“、"bc”、"cd“和"de")?
我知道围城是用来做什么的,我已经看过How does the regular expression ‘(?<=#)[^#]+(?=#)’ work?了。从2018-2019开始,谷歌Chrome就支持Lookbehind。
提前感谢

发布于 2021-08-01 23:29:03
/(?<=.*)(\w\w)(?=.*)/和/(\w\w)/是一样的,因为“在任何情况下”都是匹配的(因为它匹配空字符串)。\b、$、(?=)等)不同,所有其他表达式都是,即它们从字符串中消耗一口长度。有一些搜索游标按照这个长度进行,并且从不后退。如果找到2个符号,则此游标由2个符号进行,搜索继续进行。对于描述的行为,您需要手动移动此游标,如下所示:
const str = 'abcde';
const re = /(\w\w)/g;
let result;
while (result = re.exec(str)) {
console.log(result);
re.lastIndex--;
}
发布于 2021-08-01 23:48:02
因此,为了找到重叠的匹配,您必须将所需的模式放在一个展望中。
(?=(\w\w))示例:
const regex = /(?=(\w\w))/gm;
const str = `abcde`;
let m;
let matches = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
if (groupIndex === 1) {
matches.push(match);
}
});
}
console.log(matches);
https://stackoverflow.com/questions/68614987
复制相似问题