Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a JavaScript regular expression that matches anything except a particular string

Ok, I'm feeling pretty thick right now. Basically, I want to define a JavaScript regular expression that will match anything except precisely a particular string. So say I have the string

"dog"

or

"cat"

I want a single standalone regular expression such that it will match the string

"dogsled"

or the string

"cattle"

Just not "dog" or "cat" on its own. I've tried this, which basically says, ignore anything beginning with "cat" or "dog", which is not exactly what I need...

var pattern= /^(?!dog|cat).+/

pattern.test("cat") // false, as expected
pattern.test("dog") // false, as expected
pattern.test("bananananana") // true
pattern.test("dogsled") // false, but the regexp I want would return true

This has to be simple.... thanks!

Edit Just to clarify, I don't want to do any negation of return values to get the result I want- the regex should return false for "dog" and true for "dogsled" or false for "cat" and true for "cattle"

like image 476
VLostBoy Avatar asked Jan 13 '12 15:01

VLostBoy


1 Answers

I would opt for simply negating a match as noted in Linus Kleen's answer. However, if you absolutely must do it all in regex (or for the learning experience or something) then I think the following should work:

^((dog|cat(?!$)).+|(?!dog|cat).+)$

This uses two negative lookaheads in an alternation. The first says "Match cat or dog if it is not followed by the end of string character ($), followed by anything else". This matches dogsled and cats and things of that nature.

The second half of the alternation says "Make sure the beginning of the string (^) is not followed by dog or cat (so it doesn't start with either of those), then match anything". This gets you any word that doesn't begin with cat or dog (like banana).

Here's an example on regexpal.

like image 116
eldarerathis Avatar answered Sep 22 '22 20:09

eldarerathis