1

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.

AnOldSoul
  • 4,017
  • 12
  • 57
  • 118

1 Answers1

8

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

elixenide
  • 44,308
  • 16
  • 74
  • 100