Member-only story
Demystifying Look-Ahead and Look-Behind in Regex
Simplifying look-ahead and look-behind in Regular Expressions with easy-to-understand examples and animated GIFs
One of the concepts in Regular Expressions (Regex) that I’ve always found difficult to wrap my head around is look-arounds — which comprise look-aheads and look-behinds.
While there are plenty of articles and tutorials online explaining this concept, few do it in a way that is easy to understand, at least not to my satisfaction. Many use jargons such as “consuming groups,” “zero-width assertions,” etc., which doesn’t help those who are learning this advanced topic.
Furthermore, there is a lack of clarity over how to interpret the names of the look-arounds. For instance, for look-behind, what is “behind" relative to? What are we “looking" for? The same goes for look-ahead. As if they are not confusing enough, there are two sub-types — positive and negative — for each type of look-around.
In this article, I attempt to demystify the concepts of look-ahead and look-behind once and for all. I will avoid technical jargon and instead explain…