How does (?!) operator in regex work?

javascript, regex

Solution

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.

Problem

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.

Original source