javascript regex - 看看后面的替代方法?

新手上路,请多包涵

这是一个在大多数正则表达式实现中都能正常工作的正则表达式:

 (?<!filename)\.js$

这与 .js 匹配以 .js 结尾的字符串,除了 filename.js

Javascript 没有正则表达式回顾。有没有人能够组合一个替代的正则表达式来实现相同的结果并在 javascript 中工作?

这里有一些想法,但需要辅助功能。我希望只用一个正则表达式来实现它:http: //blog.stevenlevithan.com/archives/mimic-lookbehind-javascript

原文由 daniel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 343
2 个回答

编辑:从 ECMAScript 2018 开始, lookbehind assertions (even unbounded) are natively supported natively

在以前的版本中,您可以这样做:

 ^(?:(?!filename\.js$).)*\.js$

这明确地完成了后视表达式隐含地做的事情:如果后视表达式加上它后面的正则表达式不匹配,则检查字符串的每个字符,然后才允许该字符匹配。

 ^                 # Start of string
(?:               # Try to match the following:
 (?!              # First assert that we can't match the following:
  filename\.js    # filename.js
  $               # and end-of-string
 )                # End of negative lookahead
 .                # Match any character
)*                # Repeat as needed
\.js              # Match .js
$                 # End of string

另一个编辑:

我很痛苦地说(特别是因为这个答案已经被投票这么多)有一种更简单的方法来实现这个目标。无需检查每个字符的前瞻性:

 ^(?!.*filename\.js$).*\.js$

同样有效:

 ^                 # Start of string
(?!               # Assert that we can't match the following:
 .*               # any string,
  filename\.js    # followed by filename.js
  $               # and end-of-string
)                 # End of negative lookahead
.*                # Match any string
\.js              # Match .js
$                 # End of string

原文由 Tim Pietzcker 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题