简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM