我怎样才能得到一个正则表达式来匹配以“.js”而不是“.test.js”结尾的文件?

Dav*_*d C 5 javascript regex webpack

我正在使用 webpack,它采用正则表达式将文件送入加载器。我想从构建中排除测试文件,测试文件以.test.js. 所以,我正在寻找一个匹配index.js但不匹配的正则表达式index.test.js

我尝试使用否定回顾断言

/(?<!\.test)\.js$/
Run Code Online (Sandbox Code Playgroud)

但它说该表达式无效。

SyntaxError: Invalid regular expression: /(?<!\.test)\.js$/: Invalid group
Run Code Online (Sandbox Code Playgroud)

示例文件名:

index.js          // <-- should match
index.test.js     // <-- should not match
component.js      // <-- should match
component.test.js // <-- should not match
Run Code Online (Sandbox Code Playgroud)

Jan*_*Jan 5

你去吧:

^(?!.*\.test\.js$).*\.js$
Run Code Online (Sandbox Code Playgroud)

在 regex101.com 上查看它。


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

  • 我再次破坏你的答案,这实际上是最好的正则表达式(即唯一一个在前瞻中具有行尾位置以不捕捉中字符串 test.js 的正则表达式) (2认同)

Sag*_*r V 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"));
Run Code Online (Sandbox Code Playgroud)