不匹配 spec.ts 和 spec.tsx 但应该匹配任何其他 .ts 和 .tsx 的正则表达式 [英] Regex that doesn't match spec.ts and spec.tsx but should match any other .ts and .tsx
问题描述
我写的这个正则表达式匹配任何 .ts 或 .tsx 文件名,但不应该匹配 spec.tsx 或 spec.ts.下面是我写的正则表达式.
I wrote this regex that matches any .ts or .tsx file names but shouldn't match spec.tsx or spec.ts. Below is the regex I wrote.
(?!spec)\.(ts|tsx)$
但它无法忽略.spec.tsx 和spec.ts 文件.我在这里做错了什么?请指教.
But it fails to ignore.spec.tsx and spec.ts files. What am I doing wrong here? Please advice.
推荐答案
否定前瞻语法 ((?!...)
) 从任何位置看起来ahead在正则表达式中.因此,您的 (?!spec)
正在与该点之后的内容进行比较,就在 \.
之前.换句话说,它与文件扩展名 .ts
或 .tsx
进行比较.否定前瞻不匹配,因此整个字符串不会被拒绝为匹配项.
The negative lookahead syntax ((?!...)
) looks ahead from wherever it is in the regex. So your (?!spec)
is being compared to what follows that point, just before the \.
. In other words, it's being compared to the file extension, .ts
or .tsx
. The negative lookahead doesn't match, so the overall string is not rejected as a match.
你想要一个否定的lookbehind正则表达式:
You want a negative lookbehind regex:
(?<!spec)\.(ts|tsx)$
这是一个演示(请参阅单元测试"链接在屏幕左侧).
Here's a demo (see the "unit tests" link on the left side of the screen).
以上假设您的正则表达式风格支持负向后视;并非所有的正则表达式都可以.如果您碰巧使用了不支持负向后视的正则表达式,则可以使用更复杂的负向后视:
The above assumes that your flavor of regex supports negative lookbehinds; not all flavors of regex do. If you happen to be using a regex flavor that doesn't support negative lookbehinds, you can use a more complex negative lookahead:
^(?!.*spec\.tsx?$).*\.tsx?$
这实际上是说,从头开始,确保字符串不以 spec.ts
或 spec.tsx
结尾.如果不是't 以那个结尾,然后匹配它是否以 .ts
或 .tsx
"
This says, in effect, "Starting from the beginning, make sure the string doesn't end in spec.ts
or spec.tsx
. If it doesn't end in that, then match if it ends in .ts
or .tsx
"
这篇关于不匹配 spec.ts 和 spec.tsx 但应该匹配任何其他 .ts 和 .tsx 的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!