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.
$ 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.
Matches a form-feed character. \n. Matches a newline character. \r. Matches a carriage return character.
[] 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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With