brewster
brewster

Reputation: 4492

exclude full word with javascript regex word boundary

I'am looking to exclude matches that contain a specific word or phrase. For example, how could I match only lines 1 and 3? the \b word boundary does not work intuitively like I expected.

foo.js            # match
foo_test.js       # do not match
foo.ts            # match
fun_tset.js       # match
fun_tset_test.ts  # do not match

UPDATE

What I want to exclude is strings ending explicitly with _test before the extension. At first I had something like [^_test], but that also excludes any combination of those characters (like line 3).

Upvotes: 1

Views: 98

Answers (2)

symlink
symlink

Reputation: 12209

Adding to @pretzelhammer's answer, it looks like you want to grab strings that are file names ending in ts or js:

^(?!.*_test)(.*\.[jt]s)

The expression in the first parentheses is a negative lookahead that excludes any strings with _test, the second parentheses matches any strings that end in a period, followed by [jt] (j or t), followed by s.

Upvotes: 0

pretzelhammer
pretzelhammer

Reputation: 15105

Regex: ^(?!.*_test\.).*$

Working examples: https://regex101.com/r/HdGom7/1

Why it works: uses negative lookahead to check if _test. exists somewhere in the string, and if so doesn't match it.

Upvotes: 2

Related Questions