Problem:
To find/match all text lines that do not contain a specific string.
For example find/match all lines in a text document that do not contain word “constant”.
Solution:
^(.(?!stringToExclude))*$
or ^(.(?!constant))*$ with respect to the above example to exclude word “constant”.
Another example: in a text document containing email addresses (one address per one line) delete all non Gmail (or non .uk or whatever) addresses. Sure this can be easily done (by those capable of it) with a little programing, but lets limit the problem to just a text editor that supports regular expressions. That is, match all non-gmail address and automatically delete them (replace them with nothing) using the editors (Komodo Edit is my choice) find-replace feature. Non “gmail.com” is the email addresses to match and deleted:
match ^(.(?!gmail\.com))*$ and replace them with nothing (empty string).
Now you are left only with Gmail addresses in your document.
Explanation:
Take a line -
^ – beggining of the line
$ – end of the line
(?!stringToExclude) – negative lookahead – do not match overall if stringToExclude matches
.(?!stringToExclude) - match any character (.) provided it is not followed by the stringToExclude
(.(?!stringToExclude))* - match zero or more of the above characters (*)
Credits:
Daniel Brückners answer at stackoverflow.com
http://www.regular-expressions.info/lookaround.html#lookahead