更新时间:2021-07-30 15:51:22
否定前瞻语法 ((?!...)
) 从任何位置看起来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
"