Regex for finding text which is not preceded by another piece of text
How to use a negative lookbehind in regex
Photo by Justin Luebke on Unsplash
One of the common searches I often want to make using regex is to find a piece of text which is not preceded by another piece of text. For example, earlier today I was searching a C# file for uses of Token
but I did not want to find CancellationToken
in my results.
The regex for this is very simple:
(?<!Cancellation)Token
Given I've already stated what this regex does, you can probably instinctively see how it's structured - I'm matching the bit outside the brackets (Token
) if it's not immediately preceded by the bit inside the brackets (Cancellation
). But how does this work?
?<!
may look confusing but it is the simple key to the whole problem. This creates a negative lookbehind - a group which must not match before the main expression. In other words, this is a feature of regex which solves my problem exactly!
If you haven't used regex before and want to get started, I have previously written an article which starts from scratch and teaches you enough basic regex that you can easily start getting benefit from it: