Regex that doesn't match spec.ts and spec.tsx but should match any other .ts and .tsx

夙愿已清 提交于 2020-07-20 05:43:38

问题


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)$

But it fails to ignore.spec.tsx and spec.ts files. What am I doing wrong here? Please advice.


回答1:


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.

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?$

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"

Demo



来源:https://stackoverflow.com/questions/38473025/regex-that-doesnt-match-spec-ts-and-spec-tsx-but-should-match-any-other-ts-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!