小编典典

Javascript:否定的后向等效?

javascript

有没有办法在javascript正则表达式中实现与否定的后向等效?我需要匹配一个不以一组特定字符开头的字符串。

如果在字符串的开头找到匹配的部分,似乎无法找到执行此操作的正则表达式。负向后看似乎是唯一的答案,但是javascript没有答案。

编辑:这是我想工作的正则表达式,但它不:

(?<!([abcdefg]))m

因此它将与“ jim”或“ m”中的“ m”匹配,但与“ jam”不匹配


阅读 345

收藏
2020-04-23

共1个答案

小编典典

后向断言得到了接受入ECMAScript规范 2018年至今,它只是在实现V8。因此,如果您正在开发仅适用于Chrome的环境(例如Electron)或Node,那么今天就可以开始使用lookbehinds!

正向后方用法:

console.log(

  "$9.99  €8.47".match(/(?<=\$)\d+(\.\d*)?/) // Matches "9.99"

);

负向后使用:

console.log(

  "$9.99  €8.47".match(/(?<!\$)\d+(?:\.\d*)/) // Matches "8.47"

);

平台支持:

  • ✔V8
  • ✔Google Chrome 62.0
  • ✔Node.js 6.0 behind a flag and 9.0 without a flag
  • ❌Mozilla Firefox (SpiderMonkey) is working on it
  • ❌Microsoft was working on it for Chakra, but the next version of Edge will be built on Chromium and will thus support it
  • ❌Apple Safari (Webkit) is working on it
2020-04-23