iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
👀

Lookahead and Lookbehind in Regular Expressions

に公開
2025/05/31
2件

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 by regex.
  • (?<=regex) : Lookbehind. Matches a position preceded by regex.
(?<=<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 by regex.
  • (?<!regex) : Negative lookbehind. Matches a position not preceded by regex.
(?!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

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).

GitHubで編集を提案

Discussion

nanto_vinanto_vi

解説ありがとうございます。ツールまで紹介していただけるのは試行しやすくて助かります。

余談ですが、個人的にはどちらが「先」でどちらが「後」か、少し混乱します。

同感です。個人的にはlookbehindには「戻り読み」という訳語が好みなのですが、採用例があまり多くありません。ぱっと探して見つかるのは正規表現ライブラリ「鬼車」のドキュメントやPHPのマニュアルぐらいです。

(?=.*hoge.*)(?=.*fuga.*)(?=.*piyo.*).*

この正規表現パターンですが、hogeの直前に最長一致.*を使うと、いったん文字列(または行)の末尾まで読み込み、そこから戻ってhogeを探すことになります。最短一致.*?を使う(hogeが現れたらそこで探索を打ち切る)ほうが、効率的な正規表現パターンになります。

use strict;
use warnings;
use Benchmark qw(cmpthese);

my $text = join 'a' x 1000, 'hoge', 'fuga', 'piyo';

cmpthese(-1, {
    '.*hoge.*' => sub {
        my $v = $text =~ m/(?=.*hoge.*)(?=.*fuga.*)(?=.*piyo.*).*/;
    },
    '.*?hoge' => sub {
        my $v = $text =~ m/(?=.*?hoge)(?=.*?fuga)(?=.*?piyo).*/;
    },
});
# Perl 5.36.0での実行結果:
#               Rate .*hoge.*  .*?hoge
# .*hoge.*  133980/s       --     -94%
# .*?hoge  2096352/s    1465%       --
3
USAMI KosukeUSAMI Kosuke

コメントありがとうございます。

個人的にはlookbehindには「戻り読み」という訳語が好み

なるほど、「戻り読み」いいですね。採用事例もあるとのこと、情報ありがとうございます。

最短一致.*?を使う(hogeが現れたらそこで探索を打ち切る)ほうが、効率的な正規表現パターンになります。

指摘ありがとうございます。パフォーマンス比較もしていただいて参考になります。後ほど、本文にも追記しようと思います。