Regex Negative Lookahead, so powerful!
I am a big fan of regular expressions. They are so mysterious and elegant, I love them and hate them, cherish them and despise them. In other words they are both beautiful and nasty, but they can really get the job done. I was intrigued today when a colleague of mine was asking how to match a string but if it started with a specific sequence then do not match. In my regex coolness I said “Sure, that’s easy man!”, whipped out QuickREx in Eclipse, wrote down a quick jolt of brilliance and BAMM!! I hit the brick wall at 90! Nothing I was trying would work, characters where matched not the word:
1: ^([^search].*)dev\.domain
Basically match any incoming domain that ends with dev.domain but it should not be preceded by the word search. I really thought I nailed it with that regex, but NOOO, it matches character classes not full words. So I had to revert my humble ego and go back to the books and voila: Positive and Negative LookAhead!
Granted, some regex engines do not support look behinds, but thankfully java does. Here is a cool definition:
(?!regex)
Zero-width negative lookahead. Identical to positive lookahead, except that the overall match will only succeed if the regex inside the lookahead fails to match.
And finally and AHA!! moment. I can use the lookahead:
1: ^(?!search|training).*dev\.domain
AND BUYAAA!!! I think this can help somebody out there. It helped me!