sites
sites

Reputation: 21795

Regexp that matches when word is not found

I need a regexp that returns something (the entire sentence) when the string does NOT match a keyword.

Maybe this is strange, but I need something like this in javascript:

"any word".match(/.*(?!my key)/) => I would want ["any word"]
"my key".match(/.*(?!my key)/) => I would want null

This previous does not work.

I can't do something like, which would work:

if "any word".match(/my key/)
  return null
else
  return "any word"

because I am inside a place that receives a Regexp and executes a function if it matches.

Upvotes: 0

Views: 235

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

In your regex, .* first matches the entire string, then the lookahead assertion (?!my key) succeeds, too (because you can't match my key at the end of the string, of course).

You want

"test string".match(/^(?!.*my key).*/)

Also, you might need to use the s modifier if your test string possibly contains newlines, and you might want to use word boundaries (\b) to avoid false positives with strings like army keypad:

"test string".match(/^(?!.*\bmy key\b).*/s)

Upvotes: 1

Related Questions