问题
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