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

Zeya LT
Better Programming
9 min readApr 1, 2022

--

comic. someone swoops in screaming “I know regular expressions!” Taps on the computer, some Perl, then leaves. Other people cheer.
Image by https://xkcd.com/

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.

Comic: two people talking. one has sunglasses on. sunglasses: if you’re havin’ Perl problems, I feel bad for you son. I got 99 problems, so I used regular expressions. Now, I have 100 problems.
Image by https://xkcd.com/

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…

--

--

Zeya LT
Zeya LT

Written by Zeya LT

Data Scientist @ Grab • Former Police Officer • Master’s in Data Science & Analytics • Mid-Career Switcher • Father of Two

Responses (1)

Write a response