首页 > 解决方案 > JS 正则表达式正面向后看不匹配

问题描述

这是我要匹配的字符串和句子(提取)。

let pigs = "\X The animal 0000 I really dig \X Above all others is the pig. 222 \X Pigs are noble. Pigs are clever 3333, \X Pigs are 5555 courteous.\X However, Now and then, to break this 6666 rule, \X One meets 7777 a pig who is a fool. \X"

" Pigs are 5555 courteous."

这是我的代码的两个版本。当我在各种正则表达式检查网站上签到时,它会给出所需的匹配。但是当我在浏览器控制台中运行时,它给出了 null。我有最新的 Chrome 版本。为什么浏览器控制台不在这里输出匹配项?

pigs.match(/(?<=\\X)[^\\X]*5555[^\\X]*(?=\\X)/g);
pigs.match(/(?:\\X)[^\\X]*5555[^\\X]*(?:\\X)/g); 

标签: javascriptregexstring-matchingpositive-lookbehind

解决方案


您可以使用以下模式:

(?<=\X)(?:.(?!\X))+5555.+?(?=\X)

我改变的是:(?:.(?!\X))+- 这是非捕获组,表达式匹配一个或多个字符,后面没有\X.

此外,您错误地使用[^\\X]了 - 它只是否定类,它将匹配除\or以外的任何字符X

下面的 JS 示例:

let pigs = "\X The animal 0000 I really dig \X Above all others is the pig. 222 \X Pigs are noble. Pigs are clever 3333, \X Pigs are 5555 courteous.\X However, Now and then, to break this 6666 rule, \X One meets 7777 a pig who is a fool. \X"

let match = pigs.match(/(?<=\X)(?:.(?!\X))+5555.+?(?=\X)/g)

console.log(match)


推荐阅读