iTranslated by AI
Lookahead and Lookbehind in Regular Expressions
In this article, I will introduce "lookahead" and "lookbehind" in regular expressions.
Matching "positions" in regular expressions
Regular expressions are used for pattern matching in strings. For example, [0-9]{4} is an expression that matches a sequence of four digits.
While most regular expressions match "strings," there are expressions that match "positions" rather than "strings." These are called anchors. They are also referred to as zero-width assertions, as they are considered to match a string of length zero.
Examples of anchors include ^ (start of line), $ (end of line), and \b (word boundary).
\bcat\b

In this example, it matches cat. On the other hand, category or concat contain cat, but they do not match because the characters surrounding cat are not word boundaries.
Lookahead
Lookahead is a type of syntax that matches a position. It uses a regular expression to specify the position, enclosed in (?= and ).
a(?=..d)

This is a regular expression that matches a only if it is followed by "any two characters followed by d". In the string abracadabra, there are several as. Among these, only one satisfies the condition of being followed by "any two characters followed by d".
Lookbehind
Lookbehind is similar to lookahead.
-
(?=regex): Lookahead. Matches a position followed byregex. -
(?<=regex): Lookbehind. Matches a position preceded byregex.
(?<=<em>)cat(?=</em>)

This uses both lookbehind and lookahead to match cat only when it is enclosed by <em> and </em>.
Negative Lookahead and Negative Lookbehind
There are variations of lookahead and lookbehind as follows:
-
(?!regex): Negative lookahead. Matches a position not followed byregex. -
(?<!regex): Negative lookbehind. Matches a position not preceded byregex.
(?!2022)\d{4}

\d{4} matches a sequence of four digits, but the negative lookahead (?!2022) does not match the position before 2022. Therefore, (?!2022)\d{4} as a whole does not match 2022.
When Lookahead Is Useful (1)
In what cases is lookahead useful? As a matter of fact, there is no pattern that can only be written using lookahead.
However, there are patterns that can be written more easily using lookahead. One of them is the following pattern:
(?=.*hoge.*)(?=.*fuga.*)(?=.*piyo.*).*

This has three lookaheads before the .* regex. These three lookaheads require that the string from a certain position onwards matches all three regexes: .*hoge.*, .*fuga.*, and .*piyo.*. Therefore, as a whole, it becomes a regex that matches strings containing all three: hoge, fuga, and piyo.
In other words, using lookahead allows you to write an AND operation for multiple regexes.
By the way, how about the following as a regex that matches strings containing hoge, fuga, and piyo?
.*hoge.*fuga.*piyo.*
This only matches when the three strings appear in exactly this order. To ensure it matches regardless of the order, it would look like this (line breaks added for readability):
.*hoge.*fuga.*piyo.*|.*hoge.*piyo.*fuga.*|
.*fuga.*piyo.*hoge.*|.*fuga.*hoge.*piyo.*|
.*piyo.*hoge.*fuga.*|.*piyo.*fuga.*hoge.*
Long regexes are often difficult to read. If you know lookahead, the same regex can be written concisely as (?=.*hoge.*)(?=.*fuga.*)(?=.*piyo.*).*.
When Lookahead Is Useful (2)
Here is another useful pattern for lookahead.
Let's write a piece of code using regex that inserts a comma every three digits into a string of numbers. Here, we will use Perl as the programming language.
#!/usr/bin/perl
$text = '12345678';
$text =~ s/(?<=\d)(?=(\d\d\d)+$)/,/g;
print $text;

When executed, 12345678 is indeed replaced with 12,345,678. But why does this code work? Let's take a closer look.

(?<=\d)(?=(\d\d\d)+$) is a regex that matches a position. Because of (?<=\d), the preceding character is a digit, and because of (?=(\d\d\d)+$), it is a position where the string ends after a sequence of three digits (i.e., a multiple of 3 digits). For 12345678, it matches the two positions between 2 and 3, and between 5 and 6.
A regex that matches a position is one that matches a "zero-length string." The process of replacing the matched part with the string , is the same as inserting , at that position. Therefore, , is inserted between 2 and 3, and between 5 and 6.
If you know lookahead, you can write smart code like this.
Points to Note
Lookahead and lookbehind are relatively new features in the history of regular expressions. Therefore, please be aware that they may not be supported depending on the language or environment.
References
- Ryoma Shinya, Yusuke Suzuki, Ken Takada, Introduction to Regular Expression Technology: Latest Engine Implementation and Theoretical Background, Gijutsu-Hyohron Co., Ltd., 2015.
- Jeffrey E.F. Friedl, translated by Longtail Inc./Takahiro Nagao, Mastering Regular Expressions 3rd Edition, O'Reilly Japan, 2008.
- Jan Goyvaerts, Steven Levithan, translated by Takahiro Nagao, Regular Expressions Cookbook, O'Reilly Japan, 2010.
Useful Tools
- Expressions : A macOS app for easily testing regular expressions. The screenshots of regex in this article are from this app.
- CodeRunner : A macOS app for easily running various programming languages. The screenshots of Perl code in this article are from this app.
Supplementary Notes
This article is a rewrite of the content presented at KyotoLT Online Vol. 27 (Slightly Advanced Features of Regular Expressions).
Discussion
解説ありがとうございます。ツールまで紹介していただけるのは試行しやすくて助かります。
同感です。個人的にはlookbehindには「戻り読み」という訳語が好みなのですが、採用例があまり多くありません。ぱっと探して見つかるのは正規表現ライブラリ「鬼車」のドキュメントやPHPのマニュアルぐらいです。
この正規表現パターンですが、
hogeの直前に最長一致.*を使うと、いったん文字列(または行)の末尾まで読み込み、そこから戻ってhogeを探すことになります。最短一致.*?を使う(hogeが現れたらそこで探索を打ち切る)ほうが、効率的な正規表現パターンになります。コメントありがとうございます。
なるほど、「戻り読み」いいですね。採用事例もあるとのこと、情報ありがとうございます。
指摘ありがとうございます。パフォーマンス比較もしていただいて参考になります。後ほど、本文にも追記しようと思います。