Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does (?!) operator in regex work?

I thought I understand how regex operators work, but now I'm really confused. In simplified example, I have two strings:

mail.wow.no-1.com
mail.ololo.wow.com

I want to match first one, NOT the second. And I'm writing regex (simplified version) like this:

^mail\.(.*)(?!\.wow\.com)$

And when I run in JS method test on both those examples, it simply returns true (in sublime 2 regex search highlights both strings, that means both strings matched)

I know that I can make reverse regex, that will match second and make logic depending on this, but I just want to understand how (?!) in regex works and what am I doing wrong.

Thanks.

like image 365
alice kibin Avatar asked Aug 15 '13 09:08

alice kibin


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is \r and \n in regex?

Matches a form-feed character. \n. Matches a newline character. \r. Matches a carriage return character.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


2 Answers

You need a .* inside the lookahead (and move it in front of the .* outside the lookahead):

^mail(?!.*\.wow\.com)\.(.*)$

Otherwise, your lookahead checks only at the end of the string. And obviously, at the end of the string, there can never be a .wow.com. You could just as well move the lookahead to the beginning of the pattern now:

^(?!.*\.wow\.com)mail\.(.*)$

Working demo.

This last variant is slightly less efficient, but I find patterns a bit easier to read if lookaheads that affect the entire string are all at the beginning of the pattern.

like image 140
Martin Ender Avatar answered Sep 22 '22 13:09

Martin Ender


It's a zero width assertion. It's a negative look-ahead.

What it says it: At this position - the following can not come.

So, for example (?!q) means, the letter q can not follow right now.

like image 27
Benjamin Gruenbaum Avatar answered Sep 25 '22 13:09

Benjamin Gruenbaum