views:

257

answers:

3

I have a string A and want to test if another string B is not part of it. This is a very simple regex whose result can be inverted afterwards.

I could do:

/foobar/.test('[email protected]')

and invert it afterwards, like this:

!(/foobar/).test('[email protected]')

The problem I have is, that I need to do it within the regular expression and not with their result. Something like:

/!foobar/.test('[email protected]')

(which does not work)

In other words: the regular expression should test for a non-existence and return true in that case.

Is this possible with JavaScript?

+9  A: 

Try:

/^(?!.*foobar)/.test('[email protected]')

A (short) explanation:

^          # start of the string 
(?!        # start negative look-ahead
  .*       # zero or more characters of any kind (except line terminators)
  foobar   # foobar
)          # end negative look-ahead

So, in plain English, that regex will look from the start of the string if the string 'foobar' can be "seen". If it can be "seen" there is no* match.

* no match because it's negative look-ahead!

More about this look-ahead stuff: http://www.regular-expressions.info/lookaround.html But Note that JavaScript only supports look-aheads, no look-behinds!

Bart Kiers
Nice - could you explain that?
Ghommey
@Ghommey: I was already working on an explanation. ;)
Bart Kiers
Thx I have never seen ?! before. Great answer
Ghommey
Great, this was exactly what I needed. Haven't tried the negative lookahead in JavaScript before. Thanks a lot!
acme
+1 I was looking for a regex post of yours to upvote - It seems this is the appropriate one as it deals with look around. Thanks again.
Amarghosh
A: 

why don't you change your code instead?

SilentGhost
It's part of a validation class and I don't want to rewrite it (if not necessary).
acme
you're still rewriting it by changing the regex
SilentGhost
I'm not rewriting my function, I'm modifying the regular expression, which is the function argument. The function remains untouched, what is what I wanted to achieve:function testRegex(regex, subject) { return regex.test(subject);}
acme
A: 

If what you're searching for really isn't more complicated than a simple string like "foobar":

if (yourString.indexOf("foobar") = -1) {
  // ...
}

http://www.w3schools.com/jsref/jsref_indexOf.asp

spilth
Thanks, but it needs to be a regular expression, I just simplified the example a little bit.
acme