如何编写正则表达式以匹配以“.js”结尾但不以“.test.js”结尾的文件?

6

我正在使用webpack,它使用正则表达式将文件传递给装载器。我想排除测试文件,在这里测试文件以.test.js结尾。因此,我正在寻找一个正则表达式,它匹配index.js但不匹配index.test.js

我尝试使用负回顾断言:

/(?<!\.test)\.js$/

但是它说表达式无效。

SyntaxError: Invalid regular expression: /(?<!\.test)\.js$/: Invalid group

示例文件名:

index.js          // <-- should match
index.test.js     // <-- should not match
component.js      // <-- should match
component.test.js // <-- should not match

很久没有关注webpack了,但我似乎记得你可以跳过正则表达式,而是传递一个函数。在你的情况下,可以像这样:function (path) { return path.endsWith('.js') && !path.endsWith('test.js')} 不过我可能会把它和其他打包工具混淆了。 - Karl-Johan Sjögren
3个回答

6

请看下面:

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

regex101.com 上可以看到它的工作原理。


正如其他人所提到的,JavaScript 使用的正则表达式引擎并不支持所有功能。例如,负向前瞻 不被支持。


3
抱歉再次打断你的回答,这实际上是被提出的最佳正则表达式(即唯一一个在前瞻中具有行尾位置,以不捕获 test.js 中间字符串的正则表达式)。 - guido

2

Javascript 不支持负回顾后发表,但可支持正向/负向先行断言:

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

DEMO


2

var re=/^(?!.*test\.js).*\.js$/;
console.log(re.test("index.test.js"));
console.log(re.test("test.js"));
console.log(re.test("someother.js"));
console.log(re.test("testt.js"));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接