javascript - 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);
解决方案
您可以使用以下模式:
(?<=\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)
推荐阅读
- asp.net - EFCore 5.0 DeleteBehavior.Cascade 多个级联路径
- r - 将文件保存为 pdf 格式时,Save_kable() 不起作用
- javascript - 为什么即使 rgb 值相等,警报也会返回 false(仅考虑奇数值)
- oracle - 如何获得上个月的相同日期?
- c++ - 如何在 if else 语句中更新全局变量(C++)
- java - InvalidAlgorithmParameterException:从 Tomcat 7 升级时 trustAnchors 参数必须为非空
- rust - 烧毁 NEP-141 代币
- node.js - 如何在节点js sequelize中传递列值
- flutter - 版本解析失败,与录音机共享首选项
- javascript - 将数据从 Controller 传递到 Odoo 中的 JS