5.38.0

名前

perlretut - Perl regular expressions tutorial

perlretut - Perl の正規表現のチュートリアル

説明

This page provides a basic tutorial on understanding, creating and using regular expressions in Perl. It serves as a complement to the reference page on regular expressions perlre. Regular expressions are an integral part of the m//, s///, qr// and split operators and so this tutorial also overlaps with "Regexp Quote-Like Operators" in perlop and "split" in perlfunc.

このページでは Perl の正規表現(regular expressions)を理解し、作成し、 使用するための基本的なチュートリアルを提供します。 詳細は正規表現のリファレンスページである perlre にあります。 正規表現は演算子 m//s///qr//split の一部分であり、 本チュートリアルでは "Regexp Quote-Like Operators" in perlop"split" in perlfunc と重複する部分があります。

Perl is widely renowned for excellence in text processing, and regular expressions are one of the big factors behind this fame. Perl regular expressions display an efficiency and flexibility unknown in most other computer languages. Mastering even the basics of regular expressions will allow you to manipulate text with surprising ease.

Perl はテキスト処理のための優れた道具であると広く知られていて、 正規表現はこの名声の大きな部分です。 Perl の正規表現は他の大部分の言語で知られていない効率性や融通性を 明らかにします。 正規表現の基本的な部分をマスターすることによってさえ驚くほど簡単に テキストを操作することができるようになるでしょう。

What is a regular expression? At its most basic, a regular expression is a template that is used to determine if a string has certain characteristics. The string is most often some text, such as a line, sentence, web page, or even a whole book, but it doesn't have to be. It could be binary data, for example. Biologists often use Perl to look for patterns in long DNA sequences.

正規表現とは何でしょうか? 最も基本的な意味では、正規表現とは文字列がある特徴を持っているかを 決定するために使われるテンプレートです。 文字列はほとんどの場合、行、文、web ページ、あるいは本全体のようななんらかの テキストですが、それに限りません。 例えば、バイナリデータの場合もあります。 生物学者は長い DNA 並びからパターンを探すのにしばしば Perl を使います。

Suppose we want to determine if the text in variable, $var contains the sequence of characters m u s h r o o m (blanks added for legibility). We can write in Perl

変数 $var に入っているテキストが文字並び m u s h r o o m (空白は読みやすさのために追加しています)を 含んでいるかどうかを調べたいとします。 Perl では次のように書けます:

 $var =~ m/mushroom/

The value of this expression will be TRUE if $var contains that sequence of characters anywhere within it, and FALSE otherwise. The portion enclosed in '/' characters denotes the characteristic we are looking for. We use the term pattern for it. The process of looking to see if the pattern occurs in the string is called matching, and the "=~" operator along with the m// tell Perl to try to match the pattern against the string. Note that the pattern is also a string, but a very special kind of one, as we will see. Patterns are in common use these days; examples are the patterns typed into a search engine to find web pages and the patterns used to list files in a directory, e.g., "ls *.txt" or "dir *.*". In Perl, the patterns described by regular expressions are used not only to search strings, but to also extract desired parts of strings, and to do search and replace operations.

この式の値は、$var がこの文字並びをどこかに含んでいるなら真に、 さもなければ偽になります。 '/' 文字で囲まれた部分は、探している特徴を意味しています。 これを パターン (pattern) と呼びます。 パターンが文字列の中にあるかどうかを探す処理を マッチング (matching) と よび、 m// と共に "=~" 演算子が使われると、Perl は文字列に対してパターンを マッチングします。 パターンも文字列ですが、既に見られたとおり、とても特殊な種類であることに 注意してください。 パターンは今日広く使われています; たとえば、ウェブページを見つけ出すために 検索エンジンにタイプしたり、ディレクトリの中のファイルを リストアップするために "ls *.txt" とか "dir *.*" としたりします。 Perl では、パターンは正規表現によって記述され、文字列を探しだすだけでなく、 文字列の望みの部分を取り出したり、検索と置換の操作をするためにも使われます。

Regular expressions have the undeserved reputation of being abstract and difficult to understand. This really stems simply because the notation used to express them tends to be terse and dense, and not because of inherent complexity. We recommend using the /x regular expression modifier (described below) along with plenty of white space to make them less dense, and easier to read. Regular expressions are constructed using simple concepts like conditionals and loops and are no more difficult to understand than the corresponding if conditionals and while loops in the Perl language itself.

正規表現には抽象的で理解するのが難しいという不適切な悪名があります。 これは本当は単に表現に使われている記法が簡潔かつ濃密であるからであって、 本質的な複雑性によるものではありません。 パターンの密度を減らし、より読みやすくするために、 /x 正規表現修飾子 (後述します) と共にたくさんの空白を使うことを 勧めます。 正規表現は条件とループのような単純なコンセプトを使って構成されていて、 Perl 自身の if であるとか while のようなそれと対応するものに比べて 難しいことはありません。

This tutorial flattens the learning curve by discussing regular expression concepts, along with their notation, one at a time and with many examples. The first part of the tutorial will progress from the simplest word searches to the basic regular expression concepts. If you master the first part, you will have all the tools needed to solve about 98% of your needs. The second part of the tutorial is for those comfortable with the basics, and hungry for more power tools. It discusses the more advanced regular expression operators and introduces the latest cutting-edge innovations.

本チュートリアルでは表記に関して一度に一つずつ、そして例を多く挙げて 正規表現のコンセプトを論じることによって、学習曲線を平坦化します。 本チュートリアルの最初の部分は基本的な正規表現のコンセプトのための単純な 単語検索から始まります。 最初の部分をマスターすれば、必要とすることの 98% を解決するのに必要な ツールを得ることになるでしょう。 本チュートリアルの二番目の部分はより強力なツールのために十分なものです。 そこではより高度な正規表現演算子について論じ、最新の機能を紹介します。

A note: to save time, "regular expression" is often abbreviated as regexp or regex. Regexp is a more natural abbreviation than regex, but is harder to pronounce. The Perl pod documentation is evenly split on regexp vs regex; in Perl, there is more than one way to abbreviate it. We'll use regexp in this tutorial.

注意: "regular expression" はしばしば regexp とか regex と略されます。 regexp は regex よりも自然な略称ですが発音するのが難しいです。 Perl の pod ドキュメントでは regexp と regex が混在しています; Perl では、 略するやり方は一つではないのです。 このチュートリアルでは regexp を使うことにします(訳注: 日本語では 「正規表現」と記します)。

New in v5.22, use re 'strict' applies stricter rules than otherwise when compiling regular expression patterns. It can find things that, while legal, may not be what you intended.

use re 'strict' は v5.22 からの新機能で、正規表現 パターンをコンパイルするときに他よりもより厳密な規則を適用します。 これにより、有効ではあるけれども、意図しているものと違うかも知れないものを 見つけることができます。

パート 1: 基本

単純な単語マッチング

The simplest regexp is simply a word, or more generally, a string of characters. A regexp consisting of just a word matches any string that contains that word:

最も単純な正規表現は単なる単語、より一般的には文字の並びです。 正規表現は単語を構成する任意の文字列にマッチングする単なる単語からなります:

    "Hello World" =~ /World/;  # matches

What is this Perl statement all about? "Hello World" is a simple double-quoted string. World is the regular expression and the // enclosing /World/ tells Perl to search a string for a match. The operator =~ associates the string with the regexp match and produces a true value if the regexp matched, or false if the regexp did not match. In our case, World matches the second word in "Hello World", so the expression is true. Expressions like this are useful in conditionals:

この Perl の文が行っていることは何でしょう? "Hello World" は単純な、ダブルクォートで囲まれた文字列です。 World は正規表現であり、 // で囲まれた /World/ は Perl に対してマッチングのために文字列を検索することを指示します。 =~ という演算子は正規表現にマッチングする文字列に結び付けられ、 正規表現がマッチングすれば真の値を生成し、マッチングしなければ偽となります。 この例では、World"Hello World" の二番目の単語にマッチングするので、 式は真となります。 このような式は条件文に使うにも便利です:

    if ("Hello World" =~ /World/) {
        print "It matches\n";
    }
    else {
        print "It doesn't match\n";
    }

There are useful variations on this theme. The sense of the match can be reversed by using the !~ operator:

便利なバリエーションもあります。 マッチングの成否の意味を反転する演算子 !~ があります:

    if ("Hello World" !~ /World/) {
        print "It doesn't match\n";
    }
    else {
        print "It matches\n";
    }

The literal string in the regexp can be replaced by a variable:

正規表現中のリテラル文字列は変数に置き換えることができます:

    my $greeting = "World";
    if ("Hello World" =~ /$greeting/) {
        print "It matches\n";
    }
    else {
        print "It doesn't match\n";
    }

If you're matching against the special default variable $_, the $_ =~ part can be omitted:

特殊デフォルト変数 $_ に対してマッチングを行う場合、$_ =~ の 部分は省略できます:

    $_ = "Hello World";
    if (/World/) {
        print "It matches\n";
    }
    else {
        print "It doesn't match\n";
    }

And finally, the // default delimiters for a match can be changed to arbitrary delimiters by putting an 'm' out front:

最後に、マッチングのための // のデフォルトデリミタは 'm' を 前置することにより任意のものにすることができます:

    "Hello World" =~ m!World!;   # matches, delimited by '!'
    "Hello World" =~ m{World};   # matches, note the paired '{}'
    "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
                                 # '/' becomes an ordinary char
    "Hello World" =~ m!World!;   # マッチングする; デリミタは '!'
    "Hello World" =~ m{World};   # マッチングする; 組になっている '{}' に注意
    "/usr/bin/perl" =~ m"/perl"; # 'usr/bin' の後にマッチングする
                                 # '/' は普通の文字になっている

/World/, m!World!, and m{World} all represent the same thing. When, e.g., the quote ('"') is used as a delimiter, the forward slash '/' becomes an ordinary character and can be used in this regexp without trouble.

/World/, m!World!, m{World} はすべて同じものを表しています。 例えば '"' をデリミタとして使ったとき、スラッシュ '/' は 通常の文字となり、トラブルなしに正規表現中で使うことができます。

Let's consider how different regexps would match "Hello World":

異なる正規表現がどのように "Hello World" にマッチングするか 考えてみましょう:

    "Hello World" =~ /world/;  # doesn't match
    "Hello World" =~ /o W/;    # matches
    "Hello World" =~ /oW/;     # doesn't match
    "Hello World" =~ /World /; # doesn't match
    "Hello World" =~ /world/;  # マッチングしない
    "Hello World" =~ /o W/;    # マッチングする
    "Hello World" =~ /oW/;     # マッチングしない
    "Hello World" =~ /World /; # マッチングしない

The first regexp world doesn't match because regexps are by default case-sensitive. The second regexp matches because the substring 'o W' occurs in the string "Hello World". The space character ' ' is treated like any other character in a regexp and is needed to match in this case. The lack of a space character is the reason the third regexp 'oW' doesn't match. The fourth regexp "World " doesn't match because there is a space at the end of the regexp, but not at the end of the string. The lesson here is that regexps must match a part of the string exactly in order for the statement to be true.

最初の正規表現 world はマッチングしません; なぜなら、正規表現は デフォルトでは大文字と小文字を区別するからです。 二番目の正規表現は "Hello World" という文字列の中に 'o W' と いう部分があるのでマッチングします。 スペース ' ' は正規表現の中で他の文字と同じように扱われ、この場合 マッチングするのに必要なものです。 スペースがないことが三番目の正規表現 'oW' がマッチングしない理由です。 四番目の正規表現は "World " 正規表現の末尾にスペースがついているのに、 文字列の末尾にはスペースがないのでマッチングしません。 このレッスンでは正規表現は、文が真となるためには 正確に 順序通りに 文字列の一部としてマッチングしなければならないことを示しました。

If a regexp matches in more than one place in the string, Perl will always match at the earliest possible point in the string:

正規表現が文字列の二箇所以上にマッチングするならば、Perl は常に文字列の中で 最初に現れるものをマッチングしようとします:

    "Hello World" =~ /o/;       # matches 'o' in 'Hello'
    "That hat is red" =~ /hat/; # matches 'hat' in 'That'
    "Hello World" =~ /o/;       # 'Hello' の 'o' にマッチング
    "That hat is red" =~ /hat/; # 'That' の中の 'hat' にマッチング

With respect to character matching, there are a few more points you need to know about. First of all, not all characters can be used "as-is" in a match. Some characters, called metacharacters, are generally reserved for use in regexp notation. The metacharacters are

文字マッチングに対する関心と共に、知っておくべき幾つかのポイントが あります。 まず始めに、すべての文字がマッチングにおいて「あるがまま」に 使われるのではないということです。 メタ文字 と呼ばれる幾つかの文字が正規表現の記述に使うために 一般的に予約されています。 メタ文字には以下のものがあります

    {}[]()^$.|*+?-#\

This list is not as definitive as it may appear (or be claimed to be in other documentation). For example, "#" is a metacharacter only when the /x pattern modifier (described below) is used, and both "}" and "]" are metacharacters only when paired with opening "{" or "[" respectively; other gotchas apply.

This list is not as definitive as it may appear (or be claimed to be in other documentation). 例えば、"#" は (後述する) /x パターン修飾子が使われたときにのみ メタ文字になり、"}""]" はそれぞれ開きかっこの "{""[" と組で使われたときにのみメタ文字です; その他のコツも適用されます。

The significance of each of these will be explained in the rest of the tutorial, but for now, it is important only to know that a metacharacter can be matched as-is by putting a backslash before it:

これらの文字のそれぞれの重要性は本チュートリアルの残りの部分で 説明されますが、今のところは、メタ文字はバックスラッシュを 前置することによってそのままの文字としてマッチングさせることができることを 知っておくことが重要です:

    "2+2=4" =~ /2+2/;    # doesn't match, + is a metacharacter
    "2+2=4" =~ /2\+2/;   # matches, \+ is treated like an ordinary +
    "The interval is [0,1)." =~ /[0,1)./     # is a syntax error!
    "The interval is [0,1)." =~ /\[0,1\)\./  # matches
    "#!/usr/bin/perl" =~ /#!\/usr\/bin\/perl/;  # matches
    "2+2=4" =~ /2+2/;    # マッチングしない; + はメタ文字
    "2+2=4" =~ /2\+2/;   # マッチングする; \+ は普通の + のように扱われる
    "The interval is [0,1)." =~ /[0,1)./     # これは文法エラー!
    "The interval is [0,1)." =~ /\[0,1\)\./  # マッチングする
    "#!/usr/bin/perl" =~ /#!\/usr\/bin\/perl/;  # マッチングする

In the last regexp, the forward slash '/' is also backslashed, because it is used to delimit the regexp. This can lead to LTS (leaning toothpick syndrome), however, and it is often more readable to change delimiters.

最後の正規表現では、スラッシュ '/' もまたバックスラッシュが つけられています; なぜなら、それが正規表現のデリミタとして使われているからです。 これは LTS(leaning toothpick syndrome つまようじ大好き症候群)を 招きがちですが、読みやすくするためにデリミタを変更することが しばしばあります。

    "#!/usr/bin/perl" =~ m!#\!/usr/bin/perl!;  # easier to read
    "#!/usr/bin/perl" =~ m!#\!/usr/bin/perl!;  # より読みやすい

The backslash character '\' is a metacharacter itself and needs to be backslashed:

バックスラッシュ文字 '\' はそれ自身がメタ文字であり、 バックスラッシュをつける必要があります:

    'C:\WIN32' =~ /C:\\WIN/;   # matches
    'C:\WIN32' =~ /C:\\WIN/;   # マッチングする

In situations where it doesn't make sense for a particular metacharacter to mean what it normally does, it automatically loses its metacharacter-ness and becomes an ordinary character that is to be matched literally. For example, the '}' is a metacharacter only when it is the mate of a '{' metacharacter. Otherwise it is treated as a literal RIGHT CURLY BRACKET. This may lead to unexpected results. use re 'strict' can catch some of these.

特定のメタ文字が通常の意味として意味のない状況では、 自動的にメタ文字性がなくなり、 リテラルにマッチングする通常の文字になります。 例えば、'}' は相手となる '{' メタ文字がいる場合にのみ メタ文字になります。 さもなければこれはリテラルな RIGHT CURLY BRACKET として扱われます。 これは想定外の結果を引き起こすかもしれません。 これらの一部は use re 'strict' で捕捉できます。

In addition to the metacharacters, there are some ASCII characters which don't have printable character equivalents and are instead represented by escape sequences. Common examples are \t for a tab, \n for a newline, \r for a carriage return and \a for a bell (or alert). If your string is better thought of as a sequence of arbitrary bytes, the octal escape sequence, e.g., \033, or hexadecimal escape sequence, e.g., \x1B may be a more natural representation for your bytes. Here are some examples of escapes:

メタ文字に加え、印字することのできない文字であって エスケープシーケンス によって表現されるいくつかの ASCII 文字があります。 一般的な例では、タブを表す \t、改行を表す \n、復帰を表す \r、 ベルを表す \a があります。 文字列を任意のバイト列としてみなすのなら、\033 のような 8 進エスケープシーケンスや \x1B のような 16 進エスケープシーケンスは バイト列のより自然な表現となります。 以下にあげるのはエスケープの例です:

    "1000\t2000" =~ m(0\t2)   # matches
    "1000\n2000" =~ /0\n20/   # matches
    "1000\t2000" =~ /\000\t2/ # doesn't match, "0" ne "\000"
    "cat"   =~ /\o{143}\x61\x74/ # matches in ASCII, but a weird way
                                 # to spell cat
    "1000\t2000" =~ m(0\t2)   # マッチングする
    "1000\n2000" =~ /0\n20/   # マッチングする
    "1000\t2000" =~ /\000\t2/ # マッチングしない; "0" は "\000" ではない
    "cat"   =~ /\o{143}\x61\x74/ # ASCII でマッチングするが、cat を綴る
                                 # 変な方法

If you've been around Perl a while, all this talk of escape sequences may seem familiar. Similar escape sequences are used in double-quoted strings and in fact the regexps in Perl are mostly treated as double-quoted strings. This means that variables can be used in regexps as well. Just like double-quoted strings, the values of the variables in the regexp will be substituted in before the regexp is evaluated for matching purposes. So we have:

あなたがすでに Perl を少なからず知っているのなら、エスケープシーケンスに 付いて述べた以上のことはすでになじみ深いものかもしれません。 同じようなエスケープシーケンスはダブルクォートで囲まれた文字列で 使われていて、事実 Perl における正規表現はほとんどの場合において ダブルクォートで囲まれた文字列のように扱われます。 このことは正規表現の中で変数を使うことができるということを意味します。 ダブルクォートで囲まれた文字列のように、正規表現中の変数の値は マッチングのために正規表現が評価されるより前に置き換えが行われます。 ですから:

    $foo = 'house';
    'housecat' =~ /$foo/;      # matches
    'cathouse' =~ /cat$foo/;   # matches
    'housecat' =~ /${foo}cat/; # matches
    $foo = 'house';
    'housecat' =~ /$foo/;      # マッチングする
    'cathouse' =~ /cat$foo/;   # マッチングする
    'housecat' =~ /${foo}cat/; # マッチングする

So far, so good. With the knowledge above you can already perform searches with just about any literal string regexp you can dream up. Here is a very simple emulation of the Unix grep program:

今のところ順調です。 これまでの知識をもとに任意のリテラル文字列正規表現に関して 検索を行うことができます。 次の例は Unix の grep プログラムの 非常に単純な 模倣です。

    % cat > simple_grep
    #!/usr/bin/perl
    $regexp = shift;
    while (<>) {
        print if /$regexp/;
    }
    ^D

    % chmod +x simple_grep

    % simple_grep abba /usr/dict/words
    Babbage
    cabbage
    cabbages
    sabbath
    Sabbathize
    Sabbathizes
    sabbatical
    scabbard
    scabbards

This program is easy to understand. #!/usr/bin/perl is the standard way to invoke a perl program from the shell. $regexp = shift; saves the first command line argument as the regexp to be used, leaving the rest of the command line arguments to be treated as files. while (<>) loops over all the lines in all the files. For each line, print if /$regexp/; prints the line if the regexp matches the line. In this line, both print and /$regexp/ use the default variable $_ implicitly.

このプログラムを理解するのは簡単です。 #!/usr/bin/perl はシェルから perl プログラムを起動する標準的な方法です。 $regexp = shift; は最初のコマンドライン引数を正規表現として使うために 保存します; そして残りのコマンドライン引数はファイルとして扱うために そのままにしておきます。 while (<>) ループはすべてのファイルのすべての行に対して 実行されます。 各行において、print if /$regexp/; はその行が正規表現に マッチングしていれば行の内容を出力します。 この行で、print/$regexp/ は暗黙にデフォルト変数 $_ を 使用します。

With all of the regexps above, if the regexp matched anywhere in the string, it was considered a match. Sometimes, however, we'd like to specify where in the string the regexp should try to match. To do this, we would use the anchor metacharacters '^' and '$'. The anchor '^' means match at the beginning of the string and the anchor '$' means match at the end of the string, or before a newline at the end of the string. Here is how they are used:

これまでの正規表現では、文字列のどこかでマッチングすればマッチングしたと みなしてきました。 しかし、ときには文字列の どこで 正規表現がマッチングするのかを 指定したいときがあります。 これを行うためには、アンカー メタ文字である '^''$' を使います。 アンカー '^' は文字列の先頭でマッチングすることを意味し、アンカー '$' は文字列の末尾(あるいは文字列の末尾にある改行の前) で マッチングすることを意味します。 以下に例を挙げます:

    "housekeeper" =~ /keeper/;    # matches
    "housekeeper" =~ /^keeper/;   # doesn't match
    "housekeeper" =~ /keeper$/;   # matches
    "housekeeper\n" =~ /keeper$/; # matches
    "housekeeper" =~ /keeper/;    # マッチングする
    "housekeeper" =~ /^keeper/;   # マッチングしない
    "housekeeper" =~ /keeper$/;   # マッチングする
    "housekeeper\n" =~ /keeper$/; # マッチングする

The second regexp doesn't match because '^' constrains keeper to match only at the beginning of the string, but "housekeeper" has keeper starting in the middle. The third regexp does match, since the '$' constrains keeper to match only at the end of the string.

二番目の正規表現はマッチングしません; なぜなら、'^'keeper が文字列の 先頭にあるときにのみマッチングすることを強制しますが、"housekeeper" は その先頭以外にkeeperを含んでいます。 三番目の正規表現は、'$'keeper が文字列の末尾にあるときにのみ マッチングすることを強制しているのでマッチングします。

When both '^' and '$' are used at the same time, the regexp has to match both the beginning and the end of the string, i.e., the regexp matches the whole string. Consider

'^''$' の両方が同時に使われた場合、その正規表現は文字列の先頭と 末尾両方にマッチングする必要があります; つまり、その正規表現は文字列全体に マッチングするのです。 以下の例で考えてみましょう

    "keeper" =~ /^keep$/;      # doesn't match
    "keeper" =~ /^keeper$/;    # matches
    ""       =~ /^$/;          # ^$ matches an empty string
    "keeper" =~ /^keep$/;      # マッチングしない
    "keeper" =~ /^keeper$/;    # マッチングする
    ""       =~ /^$/;          # ^$ は空文字列にマッチングする

The first regexp doesn't match because the string has more to it than keep. Since the second regexp is exactly the string, it matches. Using both '^' and '$' in a regexp forces the complete string to match, so it gives you complete control over which strings match and which don't. Suppose you are looking for a fellow named bert, off in a string by himself:

最初の正規表現はマッチングしません; なぜなら、文字列は keep 以外のものを 持っているからです。 二番目の正規表現は正確に同じ文字列なのでマッチングします。 '^''$' を正規表現の中で使うことによって、文字列全体に マッチングすることを強制します; このため、どの文字列がマッチングしどの 文字列がマッチングしないかを完全に制御することができます。 bert という名前の仲間を探しているとしましょう:

    "dogbert" =~ /bert/;   # matches, but not what you want
    "dogbert" =~ /bert/;   # マッチングする; しかし望んだものではない
    "dilbert" =~ /^bert/;  # doesn't match, but ..
    "bertram" =~ /^bert/;  # matches, so still not good enough
    "dilbert" =~ /^bert/;  # マッチングしない; しかし…
    "bertram" =~ /^bert/;  # マッチングする; ということはまだ十分ではない
    "bertram" =~ /^bert$/; # doesn't match, good
    "dilbert" =~ /^bert$/; # doesn't match, good
    "bert"    =~ /^bert$/; # matches, perfect
    "bertram" =~ /^bert$/; # マッチングしない; よし
    "dilbert" =~ /^bert$/; # マッチングしない; よし
    "bert"    =~ /^bert$/; # マッチングする; 完璧

Of course, in the case of a literal string, one could just as easily use the string comparison $string eq 'bert' and it would be more efficient. The ^...$ regexp really becomes useful when we add in the more powerful regexp tools below.

もちろん、リテラル文字列の場合においては、文字列の比較を $string eq 'bert' を使って簡単に行うことができ、こちらのほうが より効率がよいです。 ^...$ 正規表現は以下に述べるより強力な正規表現ツールにおいて 便利になります。

文字クラスを使う

Although one can already do quite a lot with the literal string regexps above, we've only scratched the surface of regular expression technology. In this and subsequent sections we will introduce regexp concepts (and associated metacharacter notations) that will allow a regexp to represent not just a single character sequence, but a whole class of them.

先に述べたリテラル文字列の正規表現を使ってさえ多くのことができますが、 それは正規表現テクノロジーの表面をひっかいた程度に過ぎません。 このセクションと続くセクションでは、ただ一文字の文字を表すのではなく 文字のクラス全体 を表す正規表現のコンセプト (とそれに結び付けられた メタ文字表記)を紹介します。

One such concept is that of a character class. A character class allows a set of possible characters, rather than just a single character, to match at a particular point in a regexp. You can define your own custom character classes. These are denoted by brackets [...], with the set of characters to be possibly matched inside. Here are some examples:

そのようなコンセプトは 文字クラス です。 文字クラスは正規表現の特定の場所においてマッチングする可能性のある文字の 集合です(単一の文字ではありません)。 独自のカスタム文字クラスを定義することができます。 これらはブラケット [...] で表現され、マッチングする可能性のある文字の 集合はその内側に置かれます。 以下にいくつか例を挙げます:

    /cat/;       # matches 'cat'
    /[bcr]at/;   # matches 'bat, 'cat', or 'rat'
    /item[0123456789]/;  # matches 'item0' or ... or 'item9'
    "abc" =~ /[cab]/;    # matches 'a'
    /cat/;       # 'cat' にマッチング
    /[bcr]at/;   # 'bat, 'cat', 'rat' にマッチング
    /item[0123456789]/;  # 'item0' または ... または 'item9' にマッチング
    "abc" =~ /[cab]/;    # 'a' にマッチング

In the last statement, even though 'c' is the first character in the class, 'a' matches because the first character position in the string is the earliest point at which the regexp can match.

最後の文において、'c' がクラスの最初の文字であるにもかかわらず 'a' がマッチングします; なぜなら、文字列の最初の文字位置が正規表現が マッチングすることのできる最初の位置にある文字だからです。

    /[yY][eE][sS]/;      # match 'yes' in a case-insensitive way
                         # 'yes', 'Yes', 'YES', etc.
    /[yY][eE][sS]/;      # 大小文字を問わず 'yes' にマッチングする
                         # 'yes', 'Yes', 'YES' など

This regexp displays a common task: perform a case-insensitive match. Perl provides a way of avoiding all those brackets by simply appending an 'i' to the end of the match. Then /[yY][eE][sS]/; can be rewritten as /yes/i;. The 'i' stands for case-insensitive and is an example of a modifier of the matching operation. We will meet other modifiers later in the tutorial.

この正規表現は一般的な仕事を表しています: 大小文字の違いを無視しての マッチングを行います。 Perl はこのようなブラケットを取り除くやり方を提供しています; それは マッチングの終端に 'i' をつけることです。 したがって、/[yY][eE][sS]/;/yes/i; と書き換えることができます。 この 'i' は大小文字の違いを無視することを意味していて、マッチング操作の 修飾子 (modifier)の実例です。 本チュートリアルの後の方で他の修飾子がでてくることでしょう。

We saw in the section above that there were ordinary characters, which represented themselves, and special characters, which needed a backslash '\' to represent themselves. The same is true in a character class, but the sets of ordinary and special characters inside a character class are different than those outside a character class. The special characters for a character class are -]\^$ (and the pattern delimiter, whatever it is). ']' is special because it denotes the end of a character class. '$' is special because it denotes a scalar variable. '\' is special because it is used in escape sequences, just like above. Here is how the special characters ]$\ are handled:

このセクションの前のほうで、自分自身を表す通常の文字と、 それ自身を表すためには バックスラッシュ '\' が必要な特殊文字があることを見てきました。 同じことが文字クラスの中でも言えます; しかし、文字クラスの内側にある通常の 文字と特殊文字の集合は、文字クラスの外側にあるものと異なります。 文字クラスのために特殊な文字は -]\^$ (および(何であれ)デリミタ)です。 ']' は文字クラスの終端を表すので特殊です。 '$' はスカラ変数を表すので特殊です。 '\' はエスケープシーケンスで使われるので特殊です。 以下は特殊文字 ]$\ を扱うやり方です:

   /[\]c]def/; # matches ']def' or 'cdef'
   $x = 'bcr';
   /[$x]at/;   # matches 'bat', 'cat', or 'rat'
   /[\$x]at/;  # matches '$at' or 'xat'
   /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'
   /[\]c]def/; # ']def' または 'cdef' にマッチング
   $x = 'bcr';
   /[$x]at/;   # 'bat', 'cat', 'rat' にマッチング
   /[\$x]at/;  # '$at' または 'xat' にマッチング
   /[\\$x]at/; # '\at', 'bat, 'cat', 'rat' にマッチング

The last two are a little tricky. In [\$x], the backslash protects the dollar sign, so the character class has two members '$' and 'x'. In [\\$x], the backslash is protected, so $x is treated as a variable and substituted in double quote fashion.

最後の二つはちょっとトリッキーです。 [\$x] の中ではバックスラッシュはドル記号を保護しているので、 文字クラスは '$''x' という二つのメンバを持ちます。 [\\$x] ではバックラッシュが保護されているので、$x は変数として 扱われ、ダブルクォート規則に従って置換が行われます。

The special character '-' acts as a range operator within character classes, so that a contiguous set of characters can be written as a range. With ranges, the unwieldy [0123456789] and [abc...xyz] become the svelte [0-9] and [a-z]. Some examples are

特殊文字 '-' は文字クラスの中で範囲演算子として振舞います; このため、 連続した範囲の文字を一つの範囲として記述することができます。 範囲を使うことによって、[0123456789][abc...xyz] のような 見づらいものはすっきりとした [0-9] であるとか [a-z] のように 書き換えられます。 いくつか例を挙げましょう:

    /item[0-9]/;  # matches 'item0' or ... or 'item9'
    /[0-9bx-z]aa/;  # matches '0aa', ..., '9aa',
                    # 'baa', 'xaa', 'yaa', or 'zaa'
    /[0-9a-fA-F]/;  # matches a hexadecimal digit
    /[0-9a-zA-Z_]/; # matches a "word" character,
                    # like those in a Perl variable name
    /item[0-9]/;  # 'item0' ... 'item9' にマッチングする
    /[0-9bx-z]aa/;  # '0aa' ... '9aa', 
                    # 'baa', 'xaa', 'yaa', 'zaa' のいずれかにマッチングする
    /[0-9a-fA-F]/;  # 16 進数にマッチングする
    /[0-9a-zA-Z_]/; # Perl の変数名のような
                    # 「単語」文字にマッチングする

If '-' is the first or last character in a character class, it is treated as an ordinary character; [-ab], [ab-] and [a\-b] are all equivalent.

'-' が文字クラスの中の最初か最後の文字であった場合、通常の文字として 扱われます; [-ab], [ab-], [a\-b] はすべて等価です。

The special character '^' in the first position of a character class denotes a negated character class, which matches any character but those in the brackets. Both [...] and [^...] must match a character, or the match fails. Then

文字クラスの先頭の位置にある特殊文字 '^'反転文字クラス を表し、 ブラケットの中にない文字にマッチングします。 [...][^...] の両方とも、一つの文字にマッチングせねばならず、 そうでない場合にはマッチングは失敗します。 ですから

    /[^a]at/;  # doesn't match 'aat' or 'at', but matches
               # all other 'bat', 'cat, '0at', '%at', etc.
    /[^0-9]/;  # matches a non-numeric character
    /[a^]at/;  # matches 'aat' or '^at'; here '^' is ordinary
    /[^a]at/;  # 'aat' や 'at' にはマッチングしないが、その他の
               # 'bat', 'cat, '0at', '%at' などにはマッチングする
    /[^0-9]/;  # 数字以外にマッチングする
    /[a^]at/;  # 'aat' か '^at'にマッチングする; ここでは '^' は通常の文字

Now, even [0-9] can be a bother to write multiple times, so in the interest of saving keystrokes and making regexps more readable, Perl has several abbreviations for common character classes, as shown below. Since the introduction of Unicode, unless the /a modifier is in effect, these character classes match more than just a few characters in the ASCII range.

ここで、[0-9] でさえ何回も書くには面倒です; ですから、キーストロークの 数を抑えて、かつ正規表現をより読みやすくするために後述するように Perl は 一般的な文字クラスの略記法を持っています。 Unicode の導入のために、/a 修飾子が有効でない限り、これらの文字クラスは ASCII の範囲での数文字よりも多くマッチングします。

  • \d matches a digit, not just [0-9] but also digits from non-roman scripts

    \d は数字にマッチングします; 単に [0-9] だけではなく、非ローマ字 スクリプトからの数字もマッチングします

  • \s matches a whitespace character, the set [\ \t\r\n\f] and others

    \s は空白文字にマッチングします; [\ \t\r\n\f] やその他のものです

  • \w matches a word character (alphanumeric or '_'), not just [0-9a-zA-Z_] but also digits and characters from non-roman scripts

    \w は単語を構成する文字(英数字 と '_')にマッチングします; 単に [0-9a-zA-Z_] だけではなく、非ローマ字スクリプトからの数字と文字も マッチングします

  • \D is a negated \d; it represents any other character than a digit, or [^\d]

    \D\d の否定形です; 数字以外の文字、つまり [^\d] を表します。

  • \S is a negated \s; it represents any non-whitespace character [^\s]

    \S\s の否定形です; 非空白文字 [^\s] を表します。

  • \W is a negated \w; it represents any non-word character [^\w]

    \W\w の否定形です; 単語を構成しない文字 [^\w] を表します。

  • The period '.' matches any character but "\n" (unless the modifier /s is in effect, as explained below).

    ピリオド '.' は (以下に述べるように、修飾子 //s が有効でない限り) "\n" 以外の任意の文字にマッチングします。

  • \N, like the period, matches any character but "\n", but it does so regardless of whether the modifier /s is in effect.

    \N は、ピリオドのように、"\n" 以外の任意の文字にマッチングしますが、 /s 修飾子が有効かどうかに関わらずマッチングします。

The /a modifier, available starting in Perl 5.14, is used to restrict the matches of \d, \s, and \w to just those in the ASCII range. It is useful to keep your program from being needlessly exposed to full Unicode (and its accompanying security considerations) when all you want is to process English-like text. (The "a" may be doubled, /aa, to provide even more restrictions, preventing case-insensitive matching of ASCII with non-ASCII characters; otherwise a Unicode "Kelvin Sign" would caselessly match a "k" or "K".)

Perl 5.14 から利用可能の /a 修飾子は、\d, \s, \w を ASCII の 範囲に制限するために使います。 これは、英語風のテキストを処理したいだけの時にプログラムを不必要に 完全な Unicode (とそれに関連するセキュリティの配慮) にさらされないように するのに有用です。 ("a" を重ねて /aa にするとさらに制限されて、ASCII 文字の大文字小文字を 無視したマッチングで非 ASCII 文字にマッチングしなくします; さもなければ、 Unicode の "Kelvin Sign" は "k" や "K" に、大文字小文字を無視したマッチングが 成功します。)

The \d\s\w\D\S\W abbreviations can be used both inside and outside of bracketed character classes. Here are some in use:

\d\s\w\D\S\W の省略記法は大かっこ文字クラスの内側でも外側でも 使うことができます。 以下はその例です:

    /\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format
    /[\d\s]/;         # matches any digit or whitespace character
    /\w\W\w/;         # matches a word char, followed by a
                      # non-word char, followed by a word char
    /..rt/;           # matches any two chars, followed by 'rt'
    /end\./;          # matches 'end.'
    /end[.]/;         # same thing, matches 'end.'
    /\d\d:\d\d:\d\d/; # hh:mm:ss 形式の時間表記にマッチング
    /[\d\s]/;         # 数字または空白にマッチング
    /\w\W\w/;         # 非単語文字が続きさらに単語文字が続く
                      # 単語文字にマッチング
    /..rt/;           # 'rt' が続く任意の二文字にマッチング
    /end\./;          # 'end.' にマッチング
    /end[.]/;         # 同じこと; 'end.' にマッチング

Because a period is a metacharacter, it needs to be escaped to match as an ordinary period. Because, for example, \d and \w are sets of characters, it is incorrect to think of [^\d\w] as [\D\W]; in fact [^\d\w] is the same as [^\w], which is the same as [\W]. Think De Morgan's laws.

ピリオドはメタ文字なので、ピリオドそのものにマッチングさせるにはエスケープする 必要があります。 \d\w は文字の集合なので [^\d\w][\D\W] とみなすのは 間違いです; 事実、[^\d\w][^\w] と同じであり、これは [\W] と 等価です。 ド・モルガンの法則を考えてみてください。

In actuality, the period and \d\s\w\D\S\W abbreviations are themselves types of character classes, so the ones surrounded by brackets are just one type of character class. When we need to make a distinction, we refer to them as "bracketed character classes."

実情としては、ピリオドと \d\s\w\D\S\W の省略形はそれ自身ある種の 文字クラスなので、これらを大かっこで囲んだものは単にある種の文字クラスです。 これを区別する必要がある時には、これらは「大かっこ文字クラス」 (bracketed character classes)と呼びます。

An anchor useful in basic regexps is the word anchor \b. This matches a boundary between a word character and a non-word character \w\W or \W\w:

基本的な正規表現で便利なアンカーに 語アンカー (word anchor)の \b があります。 これは単語を構成する文字と単語を構成しない文字の間 \w\W\W\w の 境界にマッチングします:

    $x = "Housecat catenates house and cat";
    $x =~ /cat/;    # matches cat in 'housecat'
    $x =~ /\bcat/;  # matches cat in 'catenates'
    $x =~ /cat\b/;  # matches cat in 'housecat'
    $x =~ /\bcat\b/;  # matches 'cat' at end of string
    $x = "Housecat catenates house and cat";
    $x =~ /cat/;    # 'housecat' の cat にマッチング
    $x =~ /\bcat/;  # 'catenates' の cat にマッチング
    $x =~ /cat\b/;  # 'housecat' の cat にマッチング
    $x =~ /\bcat\b/;  # 文字列の終端の'cat'にマッチング

Note in the last example, the end of the string is considered a word boundary.

最後の例に注意してください; 文字列の終端は単語境界として認識されています。

For natural language processing (so that, for example, apostrophes are included in words), use instead \b{wb}

自然言語処理のため (そのために、例えば、アポストロフィを単語に含める) なら、 代わりに \b{wb} を使います

    "don't" =~ / .+? \b{wb} /x;  # matches the whole string

You might wonder why '.' matches everything but "\n" - why not every character? The reason is that often one is matching against lines and would like to ignore the newline characters. For instance, while the string "\n" represents one line, we would like to think of it as empty. Then

'.'"\n" 以外の任意の文字にマッチングすることに疑問を感じるかも しれません - なぜすべての文字ではないのでしょうか? その答えはマッチングがしばしば行に対して行われ、改行文字を 無視したいからです。 たとえば、文字列 "\n" が一行を表していたとして、それを空の行として みなしたいでしょう。 ですから

    ""   =~ /^$/;    # matches
    "\n" =~ /^$/;    # matches, $ anchors before "\n"
    ""   =~ /^$/;    # マッチング
    "\n" =~ /^$/;    # マッチング; "\n" は無視される
    ""   =~ /./;      # doesn't match; it needs a char
    ""   =~ /^.$/;    # doesn't match; it needs a char
    "\n" =~ /^.$/;    # doesn't match; it needs a char other than "\n"
    "a"  =~ /^.$/;    # matches
    "a\n"  =~ /^.$/;  # matches, $ anchors before "\n"
    ""   =~ /./;      # マッチングしない; キャラクタが必要
    ""   =~ /^.$/;    # マッチングしない; キャラクタが必要
    "\n" =~ /^.$/;    # マッチングしない; "\n" 以外のキャラクタが必要
    "a"  =~ /^.$/;    # マッチングする
    "a\n"  =~ /^.$/;  # マッチングする; "\n" は無視される

This behavior is convenient, because we usually want to ignore newlines when we count and match characters in a line. Sometimes, however, we want to keep track of newlines. We might even want '^' and '$' to anchor at the beginning and end of lines within the string, rather than just the beginning and end of the string. Perl allows us to choose between ignoring and paying attention to newlines by using the /s and /m modifiers. /s and /m stand for single line and multi-line and they determine whether a string is to be treated as one continuous string, or as a set of lines. The two modifiers affect two aspects of how the regexp is interpreted: 1) how the '.' character class is defined, and 2) where the anchors '^' and '$' are able to match. Here are the four possible combinations:

通常はある行において文字を数えたりマッチングしたりするときには改行を 無視したいので、この動作は便利です。 しかし、ときとして改行を保存したいときがあります。 '^''$' を文字列の先頭や末尾ではなく行の先頭や末尾に対するアンカーと したいときがあるでしょう。 Perl は /s 修飾子や /m 修飾子を使うことによって改行を無視したり 考慮したりすることを選択することを許しています。 /s/m はそれぞれ単一行(single line)と複数行(multi-line)を意味し、 文字列を連続した文字としてみなすか行の集合としてみなすかを決定します。 これら二つの修飾子は正規表現がどのように解釈されるかに関して二つの影響を 及ぼします: 1) '.' 文字クラスがどのように定義されるか 2) アンカー '^''$' がどこにマッチングできるかです。 四つの可能な組み合わせがあります:

  • no modifiers: Default behavior. '.' matches any character except "\n". '^' matches only at the beginning of the string and '$' matches only at the end or before a newline at the end.

    修飾子なし: デフォルトの動作です。 '.'"\n" 以外の任意の文字にマッチングします。 '^' は文字列の先頭にのみマッチングし、'$' は文字列の末尾もしくは 終端にある改行の直前にのみマッチングします。

  • s modifier (/s): Treat string as a single long line. '.' matches any character, even "\n". '^' matches only at the beginning of the string and '$' matches only at the end or before a newline at the end.

    s 修飾子 (/s): 文字列を一つの長い行としてみなします。 '.'"\n" を含めた任意の文字にマッチングします。 '^' は文字列の先頭にのみマッチングし、'$' は文字列の末尾もしくは 終端にある改行の直前にのみマッチングします。

  • m modifier (/m): Treat string as a set of multiple lines. '.' matches any character except "\n". '^' and '$' are able to match at the start or end of any line within the string.

    m 修飾子 (/m): 文字列を複数行の集合としてみなします。 '.'"\n" 以外の任意の文字にマッチングします。 '^''$' はそれぞれ文字列中の任意の行の先頭と末尾にマッチングします。

  • both s and m modifiers (/sm): Treat string as a single long line, but detect multiple lines. '.' matches any character, even "\n". '^' and '$', however, are able to match at the start or end of any line within the string.

    s 修飾子と m 修飾子の両方 (/sm): 文字列を単一の長い行としてみなしますが、 複数行を検出します。 '.'"\n" を含めた任意の文字にマッチングします。 しかし、'^''$' はそれぞれ文字列中の任意の行の先頭と末尾に マッチングすることが可能です。

Here are examples of /s and /m in action:

以下はアクション中の /s/m の例です:

    $x = "There once was a girl\nWho programmed in Perl\n";
    $x =~ /^Who/;   # doesn't match, "Who" not at start of string
    $x =~ /^Who/s;  # doesn't match, "Who" not at start of string
    $x =~ /^Who/m;  # matches, "Who" at start of second line
    $x =~ /^Who/sm; # matches, "Who" at start of second line
    $x =~ /^Who/;   # マッチングしない; "Who" は文字列の先頭にはない
    $x =~ /^Who/s;  # マッチングしない; "Who" は文字列の先頭にはない
    $x =~ /^Who/m;  # マッチングする; "Who" は二行目の先頭にある
    $x =~ /^Who/sm; # マッチングする; "Who" は二行目の先頭にある
    $x =~ /girl.Who/;   # doesn't match, "." doesn't match "\n"
    $x =~ /girl.Who/s;  # matches, "." matches "\n"
    $x =~ /girl.Who/m;  # doesn't match, "." doesn't match "\n"
    $x =~ /girl.Who/sm; # matches, "." matches "\n"
    $x =~ /girl.Who/;   # マッチングしない; "." は "\n" にマッチングしない
    $x =~ /girl.Who/s;  # マッチングする; "." は "\n"にマッチングする
    $x =~ /girl.Who/m;  # マッチングしない; "." は "\n" にマッチングしない
    $x =~ /girl.Who/sm; # マッチングする; "." は "\n"にマッチングする

Most of the time, the default behavior is what is wanted, but /s and /m are occasionally very useful. If /m is being used, the start of the string can still be matched with \A and the end of the string can still be matched with the anchors \Z (matches both the end and the newline before, like '$'), and \z (matches only the end):

ほとんどの場合、デフォルトの動作が望んでいるものですが、/s/m はとても便利なものです。 もし /m を使っているのなら、文字列の先頭は \A で マッチングさせることができ、文字列の末尾はアンカー \Z ('$' と 同じように、末尾と末尾にある改行の直前にマッチングします) や \z (末尾にのみマッチング)でマッチングさせることができます:

    $x =~ /^Who/m;   # matches, "Who" at start of second line
    $x =~ /\AWho/m;  # doesn't match, "Who" is not at start of string
    $x =~ /^Who/m;   # マッチングする; "Who" は二行目の先頭にある
    $x =~ /\AWho/m;  # マッチングしない; "Who" は文字列の先頭にはない
    $x =~ /girl$/m;  # matches, "girl" at end of first line
    $x =~ /girl\Z/m; # doesn't match, "girl" is not at end of string
    $x =~ /girl$/m;  # マッチングする; "girl" は一行目の末尾にある
    $x =~ /girl\Z/m; # マッチングしない; "girl" は文字列の末尾にはない
    $x =~ /Perl\Z/m; # matches, "Perl" is at newline before end
    $x =~ /Perl\z/m; # doesn't match, "Perl" is not at end of string
    $x =~ /Perl\Z/m; # マッチングする; "Perl" は末尾の直前にある改行の前にある
    $x =~ /Perl\z/m; # マッチングしない; "Perl" は文字列の末尾にはない

We now know how to create choices among classes of characters in a regexp. What about choices among words or character strings? Such choices are described in the next section.

正規表現中で文字クラスをどのように選択するかを学びました。 単語や文字並びに関する選択は? その選択は次のセクションで述べます。

あれやこれやにマッチングする

Sometimes we would like our regexp to be able to match different possible words or character strings. This is accomplished by using the alternation metacharacter '|'. To match dog or cat, we form the regexp dog|cat. As before, Perl will try to match the regexp at the earliest possible point in the string. At each character position, Perl will first try to match the first alternative, dog. If dog doesn't match, Perl will then try the next alternative, cat. If cat doesn't match either, then the match fails and Perl moves to the next position in the string. Some examples:

正規表現を異なる単語や文字並びにマッチングさせたいと考えることがあるでしょう。 これは 選択 メタ文字 '|' によって行うことができます。 dog または cat にマッチングさせるには、正規表現を dog|cat のようにします。 以前述べた通り、Perlは文字列の可能な限り最も早い位置でマッチングを 行おうとします。 それぞれの文字位置で、Perlはまずはじめに最初の選択である dog に マッチングさせることを試みます。 もし dog がマッチングしなければ、Perl は次の選択肢である cat を 試します。 cat もまたマッチングしなければ、マッチングは失敗してPerlは文字列の次の 位置に移動します。 幾つか例を挙げましょう:

    "cats and dogs" =~ /cat|dog|bird/;  # matches "cat"
    "cats and dogs" =~ /dog|cat|bird/;  # matches "cat"
    "cats and dogs" =~ /cat|dog|bird/;  # "cat" にマッチング
    "cats and dogs" =~ /dog|cat|bird/;  # "cat" にマッチング

Even though dog is the first alternative in the second regexp, cat is able to match earlier in the string.

二番目の正規表現において最初の選択肢が dog であるにもかかわらず、 cat が文字列で最初に現れるマッチング対象です。

    "cats"          =~ /c|ca|cat|cats/; # matches "c"
    "cats"          =~ /cats|cat|ca|c/; # matches "cats"
    "cats"          =~ /c|ca|cat|cats/; # "c" にマッチング
    "cats"          =~ /cats|cat|ca|c/; # "cats" にマッチング

Here, all the alternatives match at the first string position, so the first alternative is the one that matches. If some of the alternatives are truncations of the others, put the longest ones first to give them a chance to match.

ここではすべての選択肢が最初の位置でマッチングするので、最初の選択肢が マッチング対象となります。 もし一部の選択肢が他の選択肢を縮めたものであるならば、マッチングのチャンスを 与えるために最も長いものを最初に置きます。

    "cab" =~ /a|b|c/ # matches "c"
                     # /a|b|c/ == /[abc]/
    "cab" =~ /a|b|c/ # "c" にマッチング
                     # /a|b|c/ == /[abc]/

The last example points out that character classes are like alternations of characters. At a given character position, the first alternative that allows the regexp match to succeed will be the one that matches.

この最後の例は文字クラスが文字の選択に似ていることを表しています。 与えられた文字位置で、正規表現のマッチングを成功させるための 最初の選択肢はマッチングする一つとなります。

グループ化と階層的マッチング

Alternation allows a regexp to choose among alternatives, but by itself it is unsatisfying. The reason is that each alternative is a whole regexp, but sometime we want alternatives for just part of a regexp. For instance, suppose we want to search for housecats or housekeepers. The regexp housecat|housekeeper fits the bill, but is inefficient because we had to type house twice. It would be nice to have parts of the regexp be constant, like house, and some parts have alternatives, like cat|keeper.

選択は正規表現が選択肢の中から選び出すことを許しますが、それ自身は 満足できるものではありません。 その理由は、各選択肢は正規表現全体でなければならないのに、正規表現の 一部だけを選択したいときがあるからです。 たとえば、housecats か housekeepers を検索したいとしましょう。 housecat|housekeeper という正規表現はそれができます; しかし、house を 二回タイプしなければならないので効率がよくありません。 正規表現の一部分を house のように定数にできて、そして一部が cat|keeper のように選択肢を持つようにできればよいのです。

The grouping metacharacters () solve this problem. Grouping allows parts of a regexp to be treated as a single unit. Parts of a regexp are grouped by enclosing them in parentheses. Thus we could solve the housecat|housekeeper by forming the regexp as house(cat|keeper). The regexp house(cat|keeper) means match house followed by either cat or keeper. Some more examples are

グループ化 メタ文字 () はこの問題を解決します。 グループ化は正規表現の一部分を一つのユニットとして扱うことを許します。 ある正規表現の一部はカッコによって囲まれることでグループ化されます。 したがって、housecat|housekeeper は正規表現を house(cat|keeper) と することによって解決することができます。 正規表現 house(cat|keeper) は、catkeeper が後続する house にマッチングすることを意味します。 幾つか例を挙げましょう

    /(a|b)b/;    # matches 'ab' or 'bb'
    /(ac|b)b/;   # matches 'acb' or 'bb'
    /(^a|b)c/;   # matches 'ac' at start of string or 'bc' anywhere
    /(a|[bc])d/; # matches 'ad', 'bd', or 'cd'
    /(a|b)b/;    # 'ab' または 'bb' にマッチング
    /(ac|b)b/;   # 'acb' または 'bb' にマッチング
    /(^a|b)c/;   # 文字列の先頭にある 'ac' か任意の場所の'bc'にマッチング
    /(a|[bc])d/; # 'ad', 'bd', 'cd' にマッチング
    /house(cat|)/;  # matches either 'housecat' or 'house'
    /house(cat(s|)|)/;  # matches either 'housecats' or 'housecat' or
                        # 'house'.  Note groups can be nested.
    /house(cat|)/;  # 'housecat' か 'house' にマッチング
    /house(cat(s|)|)/;  # 'housecats' か 'housecat' か 'house' のいずれかに
                        # マッチング。グループがネストできることに注意
    /(19|20|)\d\d/;  # match years 19xx, 20xx, or the Y2K problem, xx
    "20" =~ /(19|20|)\d\d/;  # matches the null alternative '()\d\d',
                             # because '20\d\d' can't match
    /(19|20|)\d\d/;  # 年を表す19xx, 20xx か 2000 年問題を持つ xx にマッチング
    "20" =~ /(19|20|)\d\d/;  # 空の選択肢 '()\d\d' にマッチング
                             # '20\d\d' はマッチングできないから

Alternations behave the same way in groups as out of them: at a given string position, the leftmost alternative that allows the regexp to match is taken. So in the last example at the first string position, "20" matches the second alternative, but there is nothing left over to match the next two digits \d\d. So Perl moves on to the next alternative, which is the null alternative and that works, since "20" is two digits.

選択はグループの中でもその外側と同じように振舞います: 文字列の与えられた 場所で、正規表現がマッチングする最も左にある選択肢が選ばれます。 ですから、最後の例では最初の文字列位置で二番目の選択肢 "20" に マッチングしますが、残りの二つの数字 \d\d にマッチングするものが 残っていません。 このため、Perlは次の選択肢へと移り、"20" が二つの数字なので空の選択肢で うまくいきます。

The process of trying one alternative, seeing if it matches, and moving on to the next alternative, while going back in the string from where the previous alternative was tried, if it doesn't, is called backtracking. The term "backtracking" comes from the idea that matching a regexp is like a walk in the woods. Successfully matching a regexp is like arriving at a destination. There are many possible trailheads, one for each string position, and each one is tried in order, left to right. From each trailhead there may be many paths, some of which get you there, and some which are dead ends. When you walk along a trail and hit a dead end, you have to backtrack along the trail to an earlier point to try another trail. If you hit your destination, you stop immediately and forget about trying all the other trails. You are persistent, and only if you have tried all the trails from all the trailheads and not arrived at your destination, do you declare failure. To be concrete, here is a step-by-step analysis of what Perl does when it tries to match the regexp

ある選択肢を試し、マッチングすればそれを選んで次の選択肢へ移り、 マッチングしなければ文字列の以前の選択肢を試した場所に戻る、 という手順は バックトラッキング (backtracking)と呼ばれます。 'バックトラッキング'という単語は正規表現のマッチングが森の中の散歩に 似ていることからきています。 正規表現のマッチングが成功することは目的地にたどり着くことです。 多くの起点があり、文字列の各位置のひとつで左から右へと順序だてて 一つ一つ試します。 それぞれの起点からは多くの通り道があり、どれかはあなたが目指す場所で 他のどれかは行き止まりになっています。 歩いていて行き止まりに当たったら、あなたはもと来た道を後戻り(backtrack)して 別の道を試してみなければなりません。 目的地に着いたなら、即座に止まって他の道は忘れてしまいます。 あなたは粘り強いので、すべての起点からすべての通り道を試してそれでも 目的地に着かなければ、失敗を宣言します。 具体的に、Perl が正規表現のマッチングを試しているときに行っていることを ステップを追って説明しましょう

    "abcde" =~ /(abd|abc)(df|d|de)/;
  1. Start with the first letter in the string 'a'.

    文字列の最初の文字 'a' から始めます。

  2. Try the first alternative in the first group 'abd'.

    最初のグループの中の最初の選択肢 'abd' を試します。

  3. Match 'a' followed by 'b'. So far so good.

    'a' とそれに続く 'b' にマッチングします。よさそうです。

  4. 'd' in the regexp doesn't match 'c' in the string - a dead end. So backtrack two characters and pick the second alternative in the first group 'abc'.

    正規表現中の 'd' は文字列中の 'c' に マッチングしません - 行き止まりです。 このため、二文字後戻りして最初のグループの 二番目の選択肢である 'abc' を取り出します。

  5. Match 'a' followed by 'b' followed by 'c'. We are on a roll and have satisfied the first group. Set $1 to 'abc'.

    'a', 'b', 'c' と続けてマッチングします。 ここで最初のグループが満足されました。$1'abc' をセットします。

  6. Move on to the second group and pick the first alternative 'df'.

    二番目のグループへ移動して、最初の選択肢である 'df' を取り出します。

  7. Match the 'd'.

    'd' にマッチングします。

  8. 'f' in the regexp doesn't match 'e' in the string, so a dead end. Backtrack one character and pick the second alternative in the second group 'd'.

    正規表現中の 'f' は文字列中の 'e' にマッチングしません; 行き止まりです。 一文字後戻りして二番目のグループの二番目の選択肢 'd' を取り出します。

  9. 'd' matches. The second grouping is satisfied, so set $2 to 'd'.

    'd' にマッチングします。 二番目のグループは満足されたので、$2'd' をセットします。

  10. We are at the end of the regexp, so we are done! We have matched 'abcd' out of the string "abcde".

    正規表現の終端に達しました; これで終わりです! 文字列 "abcde" に対して 'abcd' がマッチングしました。

There are a couple of things to note about this analysis. First, the third alternative in the second group 'de' also allows a match, but we stopped before we got to it - at a given character position, leftmost wins. Second, we were able to get a match at the first character position of the string 'a'. If there were no matches at the first position, Perl would move to the second character position 'b' and attempt the match all over again. Only when all possible paths at all possible character positions have been exhausted does Perl give up and declare $string =~ /(abd|abc)(df|d|de)/; to be false.

この調査に関して注意すべき点が二、三あります。 第一に、二番目のグループの三番目の選択肢 'de' もまたマッチングしますが、 そこに行く前に停止しました - 与えられた文字の位置で、最も左のものが 優先されるからです。 第二に、文字列の最初の文字が 'a' であったのでマッチングできました。 もし最初の位置でマッチングに成功しなければ、Perl は二番目にある文字 'b' へと移動して同じことを繰り返します。 すべての可能な文字位置で、すべての可能な道筋が尽きたときにのみ Perl は マッチングをあきらめ、 $string =~ /(abd|abc)(df|d|de)/; が失敗したと宣言します。

Even with all this work, regexp matching happens remarkably fast. To speed things up, Perl compiles the regexp into a compact sequence of opcodes that can often fit inside a processor cache. When the code is executed, these opcodes can then run at full throttle and search very quickly.

これだけのことを行ってさえ、正規表現のマッチングは目立って速いものです。 検索速度を向上させるために、Perl は正規表現をコンパクトでしばしば プロセッサのキャッシュに納まるようなオペコードの並びへと変換します。 そのコードが実行されたとき、これらのオペコードはフルスロットルで 走ることができて非常にすばやく検索します。

マッチングしたものを取り出す

The grouping metacharacters () also serve another completely different function: they allow the extraction of the parts of a string that matched. This is very useful to find out what matched and for text processing in general. For each grouping, the part that matched inside goes into the special variables $1, $2, etc. They can be used just as ordinary variables:

グループ化メタ文字 () はまた、まったく異なる別の機能を有しています: マッチングした文字列の一部分を展開することができるのです。 これは一般的に、マッチングしたものを見つけ出したり、テキスト処理のために 非常に便利なものです。 それぞれのグループ化に対して、マッチングした部分が特殊変数 $1, $2 などに 格納されます。 これらの変数は通常の変数と同じように使うことができます:

    # extract hours, minutes, seconds
    if ($time =~ /(\d\d):(\d\d):(\d\d)/) {    # match hh:mm:ss format
        $hours = $1;
        $minutes = $2;
        $seconds = $3;
    }

Now, we know that in scalar context, $time =~ /(\d\d):(\d\d):(\d\d)/ returns a true or false value. In list context, however, it returns the list of matched values ($1,$2,$3). So we could write the code more compactly as

この例ではスカラコンテキストなので、 $time =~ /(\d\d):(\d\d):(\d\d)/ は真か偽の値を返します。 リストコンテキストでは、マッチングした値のリスト ($1,$2,$3) を返します。 ですから、コードをよりコンパクトに

    # extract hours, minutes, seconds
    ($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);

If the groupings in a regexp are nested, $1 gets the group with the leftmost opening parenthesis, $2 the next opening parenthesis, etc. Here is a regexp with nested groups:

正規表現中のグループ化がネストしていた場合、$1 は最も左にある 開きかっこによってグループ化されているものを取り、$2 は 次の開きかっこによるものを取り…となっていきます。 これがネストしたグループをもつ正規表現です:

    /(ab(cd|ef)((gi)|j))/;
     1  2      34

If this regexp matches, $1 contains a string starting with 'ab', $2 is either set to 'cd' or 'ef', $3 equals either 'gi' or 'j', and $4 is either set to 'gi', just like $3, or it remains undefined.

この正規表現がマッチングすると、$1'ab' で始まる文字列が入り、 $2'cd''ef' が入り、$3'gi''j' が入り、 $4$3 と同様に 'gi' が入るか、未定義のままです。

For convenience, Perl sets $+ to the string held by the highest numbered $1, $2,... that got assigned (and, somewhat related, $^N to the value of the $1, $2,... most-recently assigned; i.e. the $1, $2,... associated with the rightmost closing parenthesis used in the match).

便利のため、Perl は $+$1, $2 などの代入された番号付け変数の 最も数値の大きなものをセットします(そして、$^N には最も最近代入された $1, $2 などの値がセットされます; つまり、マッチングにおいて使われた 閉じカッコの中で最も右にあるものに結び付けられたものです)。

後方参照

Closely associated with the matching variables $1, $2, ... are the backreferences \g1, \g2,... Backreferences are simply matching variables that can be used inside a regexp. This is a really nice feature; what matches later in a regexp is made to depend on what matched earlier in the regexp. Suppose we wanted to look for doubled words in a text, like "the the". The following regexp finds all 3-letter doubles with a space in between:

マッチング変数 $1, $2 …に密接に結び付けられたものは、 後方参照 (backreferences) \g1, \g2 …です。 後方参照は正規表現の 内側 で使うことのできるマッチング変数です。 これは実に良い機能です; 正規表現の中で後でマッチングするものがそれ以前に マッチングしていたものに依存させることができます。 "the the" のように繰り返しされた単語をテキストの中から探したいとしましょう。 以下の正規表現はスペースで分けられた三文字の重複単語を見つけ出します:

    /\b(\w\w\w)\s\g1\b/;

The grouping assigns a value to \g1, so that the same 3-letter sequence is used for both parts.

グループ化は値を \g1 にセットするので、同じ三文字の並びが両方のパーツで 使われます。

A similar task is to find words consisting of two identical parts:

似たような作業としては、同じ部分が 2 回繰り返される単語を 探すというものです:

    % simple_grep '^(\w\w\w\w|\w\w\w|\w\w|\w)\g1$' /usr/dict/words
    beriberi
    booboo
    coco
    mama
    murmur
    papa

The regexp has a single grouping which considers 4-letter combinations, then 3-letter combinations, etc., and uses \g1 to look for a repeat. Although $1 and \g1 represent the same thing, care should be taken to use matched variables $1, $2,... only outside a regexp and backreferences \g1, \g2,... only inside a regexp; not doing so may lead to surprising and unsatisfactory results.

この正規表現は四文字の組み合わせ、三文字の組み合わせなどを扱うただ一つの グループ化を持っています; そして、\g1 は繰り返しを探します。 $1\g1 が同じものを表現しているにもかかわらず、マッチング変数 $1, $2 …は正規表現の 外側 のみで用い、 後方参照 \g1, \g2 …は正規表現の 内側 でのみ使うようにすべきです; そうしないと驚くような不満足な結果を招くかもしれません。

相対後方参照

Counting the opening parentheses to get the correct number for a backreference is error-prone as soon as there is more than one capturing group. A more convenient technique became available with Perl 5.10: relative backreferences. To refer to the immediately preceding capture group one now may write \g-1 or \g{-1}, the next but last is available via \g-2 or \g{-2}, and so on.

後方参照で正しい番号を得るために開きかっこを数えるということは、捕捉 グループが複数になるとすぐに間違いを起こしがちになります。 より便利なテクニックである相対後方参照が Perl 5.10 で利用可能です。 直前の捕捉グループを参照するためには \g-1\g{-1} と書き、 その手前は \g-2\g{-2}、などとなります。

Another good reason in addition to readability and maintainability for using relative backreferences is illustrated by the following example, where a simple pattern for matching peculiar strings is used:

相対後方参照を使うことの、可読性と保守性に加えたよい理由は、以下の、 特定の文字列をマッチングするための単純なパターンが使われている例で示します:

    $a99a = '([a-z])(\d)\g2\g1';   # matches a11a, g22g, x33x, etc.

Now that we have this pattern stored as a handy string, we might feel tempted to use it as a part of some other pattern:

ここで、このパターンを便利な文字列として持つことになったので、 これを他のパターンの一部として使いたいと思うかもしれません:

    $line = "code=e99e";
    if ($line =~ /^(\w+)=$a99a$/){   # unexpected behavior!
        print "$1 is valid\n";
    } else {
        print "bad line: '$line'\n";
    }

But this doesn't match, at least not the way one might expect. Only after inserting the interpolated $a99a and looking at the resulting full text of the regexp is it obvious that the backreferences have backfired. The subexpression (\w+) has snatched number 1 and demoted the groups in $a99a by one rank. This can be avoided by using relative backreferences:

しかしこれはマッチングしません; 少なくとも予想した通りには。 変数展開された $a99a を挿入した後でだけ、結果となる 正規表現のテキストを見ると、後方参照が逆効果となるのは明らかです。 部分式 (\w+) が 1 番を奪ってしまい、$a99a のグループが 1 つ格下げになります。 これは相対後方参照を使うことで回避できます:

    $a99a = '([a-z])(\d)\g{-1}\g{-2}';  # safe for being interpolated

名前付き後方参照

Perl 5.10 also introduced named capture groups and named backreferences. To attach a name to a capturing group, you write either (?<name>...) or (?'name'...). The backreference may then be written as \g{name}. It is permissible to attach the same name to more than one group, but then only the leftmost one of the eponymous set can be referenced. Outside of the pattern a named capture group is accessible through the %+ hash.

Perl 5.10 では名前付きグループと名前付き後方参照も導入されました。 捕捉グループに名前を付けるために、(?<name>...) または (?'name'...) と書けます。 後方参照は \g{name} と書けます。 複数のグループに同じ名前を付けることは出来ますが、一番左のものだけが 参照可能です。 パターンの外側では、名前付き捕捉グループは %+ ハッシュを通して アクセスできます。

Assuming that we have to match calendar dates which may be given in one of the three formats yyyy-mm-dd, mm/dd/yyyy or dd.mm.yyyy, we can write three suitable patterns where we use 'd', 'm' and 'y' respectively as the names of the groups capturing the pertaining components of a date. The matching operation combines the three patterns as alternatives:

yyyy-mm-dd, mm/dd/yyyy, dd.mm.yyyy の 3 つの形式のどれか 1 つで 与えられる日付とマッチングしなければならないと仮定すると、 'd', 'm', 'y' をそれぞれ日付の要素を捕捉するグループの名前として 使って、三つの適合するパターンを書けます。 マッチング操作は 3 つのパターンの選択として結合します:

    $fmt1 = '(?<y>\d\d\d\d)-(?<m>\d\d)-(?<d>\d\d)';
    $fmt2 = '(?<m>\d\d)/(?<d>\d\d)/(?<y>\d\d\d\d)';
    $fmt3 = '(?<d>\d\d)\.(?<m>\d\d)\.(?<y>\d\d\d\d)';
    for my $d (qw(2006-10-21 15.01.2007 10/31/2005)) {
        if ( $d =~ m{$fmt1|$fmt2|$fmt3} ){
            print "day=$+{d} month=$+{m} year=$+{y}\n";
        }
    }

If any of the alternatives matches, the hash %+ is bound to contain the three key-value pairs.

もし他のマッチングがある場合は、ハッシュ %+ は 3 つのキー-値の組が 含まれることになります。

選択捕捉グループ番号付け

Yet another capturing group numbering technique (also as from Perl 5.10) deals with the problem of referring to groups within a set of alternatives. Consider a pattern for matching a time of the day, civil or military style:

もう一つのグループの番号付けの技術 (これも Perl 5.10 からです) は、 選択の集合の中にあるグループを参照する問題を扱います。 民間形式と軍形式の時刻にマッチングするパターンを考えます:

    if ( $time =~ /(\d\d|\d):(\d\d)|(\d\d)(\d\d)/ ){
        # process hour and minute
    }

Processing the results requires an additional if statement to determine whether $1 and $2 or $3 and $4 contain the goodies. It would be easier if we could use group numbers 1 and 2 in second alternative as well, and this is exactly what the parenthesized construct (?|...), set around an alternative achieves. Here is an extended version of the previous pattern:

結果の処理には、$1$2、または $3$4 に有用なものが 含まれれているかを決定するために追加の if 文が必要です。 2 番目の選択肢にもグループ番号 1 と 2 をつけられればより簡単になります; これがまさに、選択肢の周りにかっこをつけた構造 (?|...) が 意味するものです。 これは以前のパターンの拡張版です:

  if($time =~ /(?|(\d\d|\d):(\d\d)|(\d\d)(\d\d))\s+([A-Z][A-Z][A-Z])/){
      print "hour=$1 minute=$2 zone=$3\n";
  }

Within the alternative numbering group, group numbers start at the same position for each alternative. After the group, numbering continues with one higher than the maximum reached across all the alternatives.

選択番号付けグループの中で、グループ番号はそれぞれの選択に対して 同じ位置から始まります。 このグループの後、番号付けは全ての選択の中での最大値に 1 を加えた値から 続行します。

位置情報

In addition to what was matched, Perl also provides the positions of what was matched as contents of the @- and @+ arrays. $-[0] is the position of the start of the entire match and $+[0] is the position of the end. Similarly, $-[n] is the position of the start of the $n match and $+[n] is the position of the end. If $n is undefined, so are $-[n] and $+[n]. Then this code

マッチングしたものに加えて、Perl ではマッチングしたものの位置を @-@+ という配列の中身によって提供します。 $-[0] はマッチング全体の開始位置で、$+[0] はマッチング全体の 終了位置です。 同様に、 $-[n]$n の開始位置であり $+[n] はその終了位置です。 $n が未定義であった場合には、$-[n]$+[n] もまた未定義です。 従ってこのコードは

    $x = "Mmm...donut, thought Homer";
    $x =~ /^(Mmm|Yech)\.\.\.(donut|peas)/; # matches
    foreach $exp (1..$#-) {
        no strict 'refs';
        print "Match $exp: '$$exp' at position ($-[$exp],$+[$exp])\n";
    }

prints

以下の出力を行います

    Match 1: 'Mmm' at position (0,3)
    Match 2: 'donut' at position (6,11)

Even if there are no groupings in a regexp, it is still possible to find out what exactly matched in a string. If you use them, Perl will set $` to the part of the string before the match, will set $& to the part of the string that matched, and will set $' to the part of the string after the match. An example:

グループ化を正規表現で使っていなかったとしても、文字列の中で実際に マッチングしたものを見つけ出すことが可能です。 正規表現を使ったとき、 Perl は $` に文字列のマッチングした部分より前の部分を セットし、 $& にはマッチングした部分をセットし、そして $' には マッチングした部分より後の部分をセットします。 例:

    $x = "the cat caught the mouse";
    $x =~ /cat/;  # $` = 'the ', $& = 'cat', $' = ' caught the mouse'
    $x =~ /the/;  # $` = '', $& = 'the', $' = ' cat caught the mouse'

In the second match, $` equals '' because the regexp matched at the first character position in the string and stopped; it never saw the second "the".

二番目のマッチングでは、$`'' となります; なぜなら、正規表現は文字列の最初の文字位置でマッチングして止まっているからで、 二番目の "the" を決して見ないからなのです。

If your code is to run on Perl versions earlier than 5.20, it is worthwhile to note that using $` and $' slows down regexp matching quite a bit, while $& slows it down to a lesser extent, because if they are used in one regexp in a program, they are generated for all regexps in the program. So if raw performance is a goal of your application, they should be avoided. If you need to extract the corresponding substrings, use @- and @+ instead:

コードを 5.20 より前のバージョンの Perl で動かしている場合、 $`$' を使うことは正規表現マッチングを目立って遅くさせることに 注意する価値があります; 一方 $& も遅くなる原因です; なぜなら、プログラムの中の正規表現でこれらを使ったならばプログラムの中の すべて の正規表現に対してこれらが生成されるからです。 ですから、生のパフォーマンスがあなたの作るアプリケーションのゴールで あるならば、これらを排除すべきです。 もし対応する部分文字列の展開が必要なら、代わりに @-@+ を 使いましょう:

    $` is the same as substr( $x, 0, $-[0] )
    $& is the same as substr( $x, $-[0], $+[0]-$-[0] )
    $' is the same as substr( $x, $+[0] )
    $` は substr( $x, 0, $-[0] ) と同じです
    $& は substr( $x, $-[0], $+[0]-$-[0] ) と同じです
    $' は substr( $x, $+[0] ) と同じです

As of Perl 5.10, the ${^PREMATCH}, ${^MATCH} and ${^POSTMATCH} variables may be used. These are only set if the /p modifier is present. Consequently they do not penalize the rest of the program. In Perl 5.20, ${^PREMATCH}, ${^MATCH} and ${^POSTMATCH} are available whether the /p has been used or not (the modifier is ignored), and $`, $' and $& do not cause any speed difference.

Perl 5.10 から、${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} 変数が 使えます。 これらは /p 修飾子があるときにのみ設定されます。 従って、これらはプログラムの残りの部分では不利益にはなりません。 Perl 5.20 では、${^PREMATCH}, ${^MATCH}, ${^POSTMATCH}/p は あってもなくても使えるようになり(この修飾子は無視されます)、$`, $', $& を使っても速度が変わらなくなりました。

捕捉しないグループ化

A group that is required to bundle a set of alternatives may or may not be useful as a capturing group. If it isn't, it just creates a superfluous addition to the set of available capture group values, inside as well as outside the regexp. Non-capturing groupings, denoted by (?:regexp), still allow the regexp to be treated as a single unit, but don't establish a capturing group at the same time. Both capturing and non-capturing groupings are allowed to co-exist in the same regexp. Because there is no extraction, non-capturing groupings are faster than capturing groupings. Non-capturing groupings are also handy for choosing exactly which parts of a regexp are to be extracted to matching variables:

選択肢の集合をまとめるために必要なグループは、捕捉グループとして 有用な場合もありますし、有用でない場合もあります。 有用でない場合は、これは正規表現の内外で、無駄な捕捉グループ値を 作ることになります。 非捕捉グループ化は (?:regexp) のように表記され regexp を一つの ユニットのように扱うことができるようにしますが、同時に捕捉グループを 作成することはしません。 捕捉するグループ化と捕捉しないグループ化の両方が同じ正規表現の 中で共存することができます。 部分文字列の抜き出しをしないので、非捕捉グループ化は捕捉する グループ化よりも高速です。 非捕捉グループ化はマッチング変数を使って抽出する正規表現の部分を 選択するのに便利です:

    # match a number, $1-$4 are set, but we only want $1
    /([+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)/;

    # match a number faster , only $1 is set
    /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)/;

    # match a number, get $1 = whole number, $2 = exponent
    /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE]([+-]?\d+))?)/;

Non-capturing groupings are also useful for removing nuisance elements gathered from a split operation where parentheses are required for some reason:

非捕捉グループ化は、なんらかの理由でかっこが必要なところで、split 操作が もたらす不愉快な要素を取り除くのにも便利です:

    $x = '12aba34ba5';
    @num = split /(a|b)+/, $x;    # @num = ('12','a','34','a','5')
    @num = split /(?:a|b)+/, $x;  # @num = ('12','34','5')

In Perl 5.22 and later, all groups within a regexp can be set to non-capturing by using the new /n flag:

Perl 5.22 以降では、正規表現中の全てのグループは、新しい /n フラグを使うことで非捕捉になります:

    "hello" =~ /(hi|hello)/n; # $1 is not set!

See "n" in perlre for more information.

さらなる情報については "n" in perlre を参照してください。

マッチングの繰り返し

The examples in the previous section display an annoying weakness. We were only matching 3-letter words, or chunks of words of 4 letters or less. We'd like to be able to match words or, more generally, strings of any length, without writing out tedious alternatives like \w\w\w\w|\w\w\w|\w\w|\w.

先のセクションの例では、腹立たしい弱点が明らかになりました。 三文字の単語か、四文字以下の文字の塊にだけマッチングしていました。 \w\w\w\w|\w\w\w|\w\w|\w のような長たらしい選択を書くことなしに任意の 長さの単語やより一般的には、文字列にマッチングさせたいのです。

This is exactly the problem the quantifier metacharacters '?', '*', '+', and {} were created for. They allow us to delimit the number of repeats for a portion of a regexp we consider to be a match. Quantifiers are put immediately after the character, character class, or grouping that we want to specify. They have the following meanings:

これは、'?', '*', '+', {} といった 量指定子 (quantifier) メタ文字が作られる元となった問題です。 これらはマッチングさせたいと考えている正規表現の一部分の繰り返し回数を 指定できます。 量指定子は繰り返しを指定したい文字、文字クラス、またはグループの直後に 置きます。 これらは以下のような意味があります:

  • a? means: match 'a' 1 or 0 times

    a? は: 'a' または空文字列にマッチングします。

  • a* means: match 'a' 0 or more times, i.e., any number of times

    a* は: 'a' のゼロ回以上の繰り返しにマッチングします。

  • a+ means: match 'a' 1 or more times, i.e., at least once

    a+ は: 'a' の一回以上の繰り返しにマッチングします。

  • a{n,m} means: match at least n times, but not more than m times.

    a{n,m} は: n 回以上 m 回以下の繰り返しにマッチングします。

  • a{n,} means: match at least n or more times

    a{n,} は: n 回以上の繰り返しにマッチングします。

  • a{,n} means: match at most n times, or fewer

    a{,n} は: n 回以下の繰り返しにマッチングします。

  • a{n} means: match exactly n times

    a{n} は: n 回の繰り返しにマッチングします。

If you like, you can add blanks (tab or space characters) within the braces, but adjacent to them, and/or next to the comma (if any).

もし好むなら、中かっこの内側隣接する部分や、カンマ(もしあれば)の次に、 空白(タブかスペース文字) を追加できます。

Here are some examples:

以下にいくつか例を挙げます:

    /[a-z]+\s+\d*/;  # match a lowercase word, at least one space, and
                     # any number of digits
    /(\w+)\s+\g1/;    # match doubled words of arbitrary length
    /y(es)?/i;       # matches 'y', 'Y', or a case-insensitive 'yes'
    $year =~ /^\d{2,4}$/;  # make sure year is at least 2 but not more
                           # than 4 digits
    $year =~ /^\d{ 2, 4 }$/;    # Same; for those who like wide open
                                # spaces.
    $year =~ /^\d{2, 4}$/;      # Same.
    $year =~ /^\d{4}$|^\d{2}$/; # better match; throw out 3-digit dates
    $year =~ /^\d{2}(\d{2})?$/; # same thing written differently.
                                # However, this captures the last two
                                # digits in $1 and the other does not.
    /[a-z]+\s+\d*/;  # 小文字の単語、幾つかの空白、それに続く任意の長さの
                     # 数字にマッチング
    /(\w+)\s+\g1/;   # 任意の長さの単語の重複にマッチング
    /y(es)?/i;       # 'y', 'Y', または大小文字を無視して 'yes' にマッチング
    $year =~ /^\d{2,4}$/;  # 年が少なくとも2桁あるが最大でも4桁になるように
                           # する
    $year =~ /^\d{ 2, 4 }$/;    # 同じ; 広く空いたスペースが好きな
                                # 人用。
    $year =~ /^\d{2, 4}$/;      # 同じ。
    $year =~ /^\d{4}|\d{2}$/;   # もっと良い; 3 桁をはじく
    $year =~ /^\d{2}(\d{2})?$/; # 同じことの違うやり方。
                                # しかし、この例では $1 を生成する;
                                # その他は生成しない。

    % simple_grep '^(\w+)\g1$' /usr/dict/words   # isn't this easier?
    beriberi
    booboo
    coco
    mama
    murmur
    papa

For all of these quantifiers, Perl will try to match as much of the string as possible, while still allowing the regexp to succeed. Thus with /a?.../, Perl will first try to match the regexp with the 'a' present; if that fails, Perl will try to match the regexp without the 'a' present. For the quantifier '*', we get the following:

これらの量指定子のすべてで、Perl は正規表現のマッチングが成功するのを許す範囲で 可能な限りの文字列をマッチングさせようとします。 したがって、/a?.../ があったとき、Perl は最初に 'a' があるものとして 正規表現のマッチングを試みます; もしそれが失敗したら、Perl は 'a' が ないものとして正規表現のマッチングを試みます。 量指定子 '*' に関して、以下のようになります:

    $x = "the cat in the hat";
    $x =~ /^(.*)(cat)(.*)$/; # matches,
                             # $1 = 'the '
                             # $2 = 'cat'
                             # $3 = ' in the hat'

Which is what we might expect, the match finds the only cat in the string and locks onto it. Consider, however, this regexp:

これはおそらく期待したもので、文字列の中の cat だけを見つけ出して マッチングします。 しかし、次の例で考えてみましょう:

    $x =~ /^(.*)(at)(.*)$/; # matches,
                            # $1 = 'the cat in the h'
                            # $2 = 'at'
                            # $3 = ''   (0 characters match)

One might initially guess that Perl would find the at in cat and stop there, but that wouldn't give the longest possible string to the first quantifier .*. Instead, the first quantifier .* grabs as much of the string as possible while still having the regexp match. In this example, that means having the at sequence with the final at in the string. The other important principle illustrated here is that, when there are two or more elements in a regexp, the leftmost quantifier, if there is one, gets to grab as much of the string as possible, leaving the rest of the regexp to fight over scraps. Thus in our example, the first quantifier .* grabs most of the string, while the second quantifier .* gets the empty string. Quantifiers that grab as much of the string as possible are called maximal match or greedy quantifiers.

Perl は catat を見つけて、そこでストップするだろうと考える人が いるかもしれませんが、それでは最初の量指定子 .* に可能な限りの長い 文字列を与えてはいません。 その代わりに、最初の量指定子 .* は正規表現がマッチングする範囲で可能な限りの 長い文字列をつかみとります。 この例では at が文字列の最後の at になるということを意味します。 ここで明らかになるもう一つの重要な規則は二つ以上の要素が正規表現の中に あるときには、最も左にある 量指定子が可能な限りの長さの文字列を つかみとり、正規表現の残りの部分がどうであるかは放っておくというものです。 したがってこの例では、最初の量指定子 .* は文字列のほとんどをつかみ、 二番目の量指定子 .* は空文字列をつかみます。 可能な限りの文字列をつかみとる量指定子は 最長マッチング とか 貪欲 (greedy) であると呼ばれます。

When a regexp can match a string in several different ways, we can use the principles above to predict which way the regexp will match:

正規表現が幾つかの異なる道筋で文字列にマッチングすることが可能なとき、 正規表現がどのようにマッチングするかを予測するために以下の法則を 使うことができます:

  • Principle 0: Taken as a whole, any regexp will be matched at the earliest possible position in the string.

    法則 0: 全体で、任意の正規表現は文字列中の可能な限り先頭に近い場所で マッチングする。

  • Principle 1: In an alternation a|b|c..., the leftmost alternative that allows a match for the whole regexp will be the one used.

    法則 1: 選択 a|b|c... の中で、正規表現全体がマッチングする中で最も左の 選択肢が使われる。

  • Principle 2: The maximal matching quantifiers '?', '*', '+' and {n,m} will in general match as much of the string as possible while still allowing the whole regexp to match.

    法則 2: 最大マッチング量指定子 '?', '*', '+', {n,m} は 正規表現全体がマッチングする中で最も長い文字列にマッチングする。

  • Principle 3: If there are two or more elements in a regexp, the leftmost greedy quantifier, if any, will match as much of the string as possible while still allowing the whole regexp to match. The next leftmost greedy quantifier, if any, will try to match as much of the string remaining available to it as possible, while still allowing the whole regexp to match. And so on, until all the regexp elements are satisfied.

    法則 3: 正規表現の中に二つ以上の要素があったならば、貪欲な量指定子が もしあれば、その中で最も左にあるものが正規表現全体がマッチングする条件に おいて可能な限りの長さでマッチングする。 次の貪欲な量指定子があれば、それは残りの中で正規表現全体がマッチングする 条件において最も長い文字列にマッチングする。 これをすべての正規表現要素が満足されるまで繰り返す。

As we have seen above, Principle 0 overrides the others. The regexp will be matched as early as possible, with the other principles determining how the regexp matches at that earliest character position.

すでに見たように、法則 0 は他のものを上書きしています。 正規表現は可能な限り早い地点でマッチングしようとし、他の法則はその正規表現が どのようにその最も早く現れた文字位置でマッチングするかを決定しています。

Here is an example of these principles in action:

以下はこれらの法則をアクションの中で示した例です:

    $x = "The programming republic of Perl";
    $x =~ /^(.+)(e|r)(.*)$/;  # matches,
                              # $1 = 'The programming republic of Pe'
                              # $2 = 'r'
                              # $3 = 'l'

This regexp matches at the earliest string position, 'T'. One might think that 'e', being leftmost in the alternation, would be matched, but 'r' produces the longest string in the first quantifier.

この正規表現は最も早い文字列位置 'T' でマッチングします。 選択の中で最も左にある 'e' がマッチングすると考えた人が いるかもしれませんが、'r' が最初の量指定子に関して最長の文字列を 生成します。

    $x =~ /(m{1,2})(.*)$/;  # matches,
                            # $1 = 'mm'
                            # $2 = 'ing republic of Perl'

Here, The earliest possible match is at the first 'm' in programming. m{1,2} is the first quantifier, so it gets to match a maximal mm.

ここで、最も早い可能な位置は programming の中の最初の 'm' です。 m{1,2} は最初の量指定子なので、最も長い mm にマッチングするのです。

    $x =~ /.*(m{1,2})(.*)$/;  # matches,
                              # $1 = 'm'
                              # $2 = 'ing republic of Perl'

Here, the regexp matches at the start of the string. The first quantifier .* grabs as much as possible, leaving just a single 'm' for the second quantifier m{1,2}.

これは、文字列の先頭で正規表現はマッチングします。 最初の量指定子 .* は可能な限りの部分をつかみとり、二番目の量指定子 m{1,2} のためには 'm' 一文字しか残しません。

    $x =~ /(.?)(m{1,2})(.*)$/;  # matches,
                                # $1 = 'a'
                                # $2 = 'mm'
                                # $3 = 'ing republic of Perl'

Here, .? eats its maximal one character at the earliest possible position in the string, 'a' in programming, leaving m{1,2} the opportunity to match both 'm''s. Finally,

この例では、.? は文字列の中で可能な限り早い場所での最大一文字、つまり programming の中の 'a' をつかみとります; m{1,2} は両方の 'm' に マッチングする機会を与えられます。 最終的に、

    "aXXXb" =~ /(X*)/; # matches with $1 = ''

because it can match zero copies of 'X' at the beginning of the string. If you definitely want to match at least one 'X', use X+, not X*.

そしてこうなるわけは、文字列の先頭にある 'X' のゼロ回の繰り返しに マッチングすることができるからです。 少なくとも一つの 'X' にマッチングさせたいのであるなら、X* ではなく X+ を使いましょう。

Sometimes greed is not good. At times, we would like quantifiers to match a minimal piece of string, rather than a maximal piece. For this purpose, Larry Wall created the minimal match or non-greedy quantifiers ??, *?, +?, and {}?. These are the usual quantifiers with a '?' appended to them. They have the following meanings:

貪欲であることがよくない場合もあります。 文字列の最大の部分ではなく 最小の部分にマッチングする量指定子が欲しいときが あります。 この目的のために、Larry Wall は 最小マッチング(minimal match) あるいは 無欲な(non-greedy) 量指定子 ??, *?, +?, {}? を 作り出しました。 これらは通常の量指定子に '?' を付け加えたものです。 これらは以下のような意味があります:

  • a?? means: match 'a' 0 or 1 times. Try 0 first, then 1.

    a?? は: 0 回か 1 回の 'a' にマッチングします。 はじめに 0 回を試し、それから 1 回を試します。

  • a*? means: match 'a' 0 or more times, i.e., any number of times, but as few times as possible

    a*? は: 'a' のゼロ回以上の繰り返しにマッチングします; 任意回の繰り返しができますが、可能な限り少ない回数になります。

  • a+? means: match 'a' 1 or more times, i.e., at least once, but as few times as possible

    a+? は: 'a' の一回以上の繰り返しにマッチングします; 一回以上の任意回の繰り返しができますが、可能な限り少ない回数になります。

  • a{n,m}? means: match at least n times, not more than m times, as few times as possible

    a{n,m}? は: n 回以上 m 回以下の繰り返しにマッチングしますが、可能な 限り少ない回数になります。

  • a{n,}? means: match at least n times, but as few times as possible

    a{n,}? は: 少なくとも n 回の繰り返しにマッチングしますが、可能な限り 少ない回数になります。

  • a{,n}? means: match at most n times, but as few times as possible

    a{,n}? は: 最大 n 回の繰り返しにマッチングしますが、可能な限り 少ない回数になります。

  • a{n}? means: match exactly n times. Because we match exactly n times, a{n}? is equivalent to a{n} and is just there for notational consistency.

    a{n}? は: ちょうど n 回の繰り返しにマッチングします。 ちょうど n 回なので、a{n}?a{n} と等価であり、一貫性のためだけに 存在します。

Let's look at the example above, but with minimal quantifiers:

先の例を最小量指定子を使ったものにしてみましょう:

    $x = "The programming republic of Perl";
    $x =~ /^(.+?)(e|r)(.*)$/; # matches,
                              # $1 = 'Th'
                              # $2 = 'e'
                              # $3 = ' programming republic of Perl'

The minimal string that will allow both the start of the string '^' and the alternation to match is Th, with the alternation e|r matching 'e'. The second quantifier .* is free to gobble up the rest of the string.

マッチングするために文字列の開始位置 '^' と選択の両方を満足する最小の 文字列は Th で、選択 e|r'e' にマッチングします。 二番目の量指定子 .* は文字列の残りから自由につかみとることができます。

    $x =~ /(m{1,2}?)(.*?)$/;  # matches,
                              # $1 = 'm'
                              # $2 = 'ming republic of Perl'

The first string position that this regexp can match is at the first 'm' in programming. At this position, the minimal m{1,2}? matches just one 'm'. Although the second quantifier .*? would prefer to match no characters, it is constrained by the end-of-string anchor '$' to match the rest of the string.

この正規表現がマッチングすることのできる文字列の最初の位置は programming の中の最初の 'm' です。 この位置で、最小マッチング m{1,2}? はただ一つの 'm' です。 二番目の量指定子 .*? が空にマッチングしようとしますがそれは文字列の 終端アンカー '$' が阻止して、文字列の残りにマッチングします。

    $x =~ /(.*?)(m{1,2}?)(.*)$/;  # matches,
                                  # $1 = 'The progra'
                                  # $2 = 'm'
                                  # $3 = 'ming republic of Perl'

In this regexp, you might expect the first minimal quantifier .*? to match the empty string, because it is not constrained by a '^' anchor to match the beginning of the word. Principle 0 applies here, however. Because it is possible for the whole regexp to match at the start of the string, it will match at the start of the string. Thus the first quantifier has to match everything up to the first 'm'. The second minimal quantifier matches just one 'm' and the third quantifier matches the rest of the string.

この正規表現において、最小量指定子 .*? は空文字列にマッチングすると 考えるかもしれませんが、'^' アンカーが単語の先頭にマッチングすることを 強制していません。 法則 0 がここで適用されます。 文字列の先頭で正規表現全体をマッチングさせることが可能なので、文字列の先頭で マッチング します。 したがって、最初の量指定子は最初の 'm' までにマッチングします。 二番目の最小量指定子はただ一文字の 'm' にマッチングして、三番目の量指定子が 文字列の残りにマッチングします。

    $x =~ /(.??)(m{1,2})(.*)$/;  # matches,
                                 # $1 = 'a'
                                 # $2 = 'mm'
                                 # $3 = 'ing republic of Perl'

Just as in the previous regexp, the first quantifier .?? can match earliest at position 'a', so it does. The second quantifier is greedy, so it matches mm, and the third matches the rest of the string.

先の正規表現と同じようですが、最初の量指定子 .?? は最初の 'a' の 位置でマッチングできるのでそうします。 二番目の量指定子は貪欲なので mm にマッチングし、三番目のものが文字列の 残りにマッチングします。

We can modify principle 3 above to take into account non-greedy quantifiers:

先に挙げた法則 3 を、無欲な量指定子を考慮したものにするために修正します:

  • Principle 3: If there are two or more elements in a regexp, the leftmost greedy (non-greedy) quantifier, if any, will match as much (little) of the string as possible while still allowing the whole regexp to match. The next leftmost greedy (non-greedy) quantifier, if any, will try to match as much (little) of the string remaining available to it as possible, while still allowing the whole regexp to match. And so on, until all the regexp elements are satisfied.

    法則 3: 正規表現の中に二つ以上の要素があったならば、貪欲な量指定子(もしくは 無欲な量指定子)がもしあれば、その中で最も左にあるものが 正規表現全体がマッチングする条件において可能な限りの長さでマッチングする。 次の貪欲な量指定子(もしくは無欲な量指定子)があれば、それは残りの中で 正規表現全体がマッチングする条件において最も長い(最も短い)文字列にマッチングする。 これをすべての正規表現要素が満足されるまで繰り返す。

Just like alternation, quantifiers are also susceptible to backtracking. Here is a step-by-step analysis of the example

選択と同じように、量指定子もまたバックトラッキングを行う可能性があります。 以下はステップごとに追った例です

    $x = "the cat in the hat";
    $x =~ /^(.*)(at)(.*)$/; # matches,
                            # $1 = 'the cat in the h'
                            # $2 = 'at'
                            # $3 = ''   (0 matches)
  1. Start with the first letter in the string 't'.

    文字列の最初の文字 't' で始まります。

  2. The first quantifier '.*' starts out by matching the whole string "the cat in the hat".

    最初の量指定子 '.*' は文字列全体 "the cat in the hat" に まずはじめにマッチングします。

  3. 'a' in the regexp element 'at' doesn't match the end of the string. Backtrack one character.

    正規表現要素 'at''a' は文字列の末尾にマッチングしません。 一文字後戻りします。

  4. 'a' in the regexp element 'at' still doesn't match the last letter of the string 't', so backtrack one more character.

    正規表現要素 'at''a' は文字列の最後の文字 't' に マッチングしないので、更に一文字後戻りします。

  5. Now we can match the 'a' and the 't'.

    ここで 'a''t' にマッチングできます。

  6. Move on to the third element '.*'. Since we are at the end of the string and '.*' can match 0 times, assign it the empty string.

    三番目の要素 '.*' に移ります。 文字列の末尾に位置していて、'.*' は 0 回の繰り返しに マッチングすることができるので空文字列を代入します。

  7. We are done!

    完了!

Most of the time, all this moving forward and backtracking happens quickly and searching is fast. There are some pathological regexps, however, whose execution time exponentially grows with the size of the string. A typical structure that blows up in your face is of the form

ほとんどの場合、前方への移動と後戻りが起こったときには迅速に行われ、 検索は高速です。 しかしながら、中には文字列の長さに応じて指数的に実行時間が延びるような 病理学的(pathological)な正規表現もあります。 そのようなものの例は以下のようなものです

    /(a|b+)*/;

The problem is the nested indeterminate quantifiers. There are many different ways of partitioning a string of length n between the '+' and '*': one repetition with b+ of length n, two repetitions with the first b+ length k and the second with length n-k, m repetitions whose bits add up to length n, etc. In fact there are an exponential number of ways to partition a string as a function of its length. A regexp may get lucky and match early in the process, but if there is no match, Perl will try every possibility before giving up. So be careful with nested '*''s, {n,m}'s, and '+''s. The book Mastering Regular Expressions by Jeffrey Friedl gives a wonderful discussion of this and other efficiency issues.

問題は不確定のネストした量指定子があることです。 '+''*' の間にある長さ n の文字列には複数の異なる分け方が存在します: 一つは長さ n の b+ で、二つ目は長さ k の b+ と n-k の長さのもの、 繰り返し m は長さ n まで加える、などです。 長さの関数として文字列を分割する方法の数は指数的な数になります。 正規表現は幸運なときには処理の早い段階でマッチングに成功するかもしれませんが、 マッチングしなかった場合には Perl は音を上げるまで すべての 可能性を 試します。 ですから、ネストした '*', {n,m}, '+' には注意してください。 Jeffrey Friedl による Mastering Regular Expressions (邦訳 「詳説正規表現」) という本はこういった効率の問題についてすばらしい 解説をしています。

絶対最大量指定子

Backtracking during the relentless search for a match may be a waste of time, particularly when the match is bound to fail. Consider the simple pattern

マッチングのための容赦ない検索中のバックトラッキングは時間の無駄の場合が あります; とくにマッチングが失敗する運命にあるときはそうです。 簡単なパターンを考えてみます

    /^\w+\s+\w+$/; # a word, spaces, a word

Whenever this is applied to a string which doesn't quite meet the pattern's expectations such as "abc " or "abc def ", the regexp engine will backtrack, approximately once for each character in the string. But we know that there is no way around taking all of the initial word characters to match the first repetition, that all spaces must be eaten by the middle part, and the same goes for the second word.

これが、"abc ""abc def " のような、パターンが 想定していなかったような文字列に適用されると、正規表現エンジンは 文字列のそれぞれの文字に対してほぼ 1 回バックトラックを行います。 しかし、私たちは 全ての 最初の単語文字列が最初の繰り返しにマッチングし、 全ての 空白が中間の部分で消費され、2 番目の単語も同じように なるしかない、ということを知っています。

With the introduction of the possessive quantifiers in Perl 5.10, we have a way of instructing the regexp engine not to backtrack, with the usual quantifiers with a '+' appended to them. This makes them greedy as well as stingy; once they succeed they won't give anything back to permit another solution. They have the following meanings:

Perl 5.10 での 絶対最大量指定子 の導入によって、 普通の量指定子に '+' を追加することで、正規表現エンジンに バックトラックしないように指示することができるようになります。 これは貪欲であるのと同様出し惜しみをするようにします; 一旦マッチングすると、 他の解決策のために手放すということをしなくなります。 これらは以下のような意味があります:

  • a{n,m}+ means: match at least n times, not more than m times, as many times as possible, and don't give anything up. a?+ is short for a{0,1}+

    a{n,m}+ は: 最小で n 回、最大で m 回の間で出来るだけたくさん マッチングし、そして何も手放しません。 a?+a{0,1}+ の省略形です。

  • a{n,}+ means: match at least n times, but as many times as possible, and don't give anything up. a++ is short for a{1,}+.

    a{n,}+ は: 最小で n 回で出来るだけたくさんマッチングし、 そして何も手放しません。 a++a{1,}+ の省略形です。

  • a{,n}+ means: match as many times as possible up to at most n times, and don't give anything up. a*+ is short for a{0,}+.

    a{,n}+ は: 最大で n 回で出来るだけたくさんマッチングし、 そして何も手放しません。 a*+a{0,}+ の省略形です。

  • a{n}+ means: match exactly n times. It is just there for notational consistency.

    a{n}+ は: 正確に n 回にマッチングします。 これは単に一貫性のためにあります。

These possessive quantifiers represent a special case of a more general concept, the independent subexpression, see below.

これらの絶対最大量指定子は、以下で述べる、より一般的な概念である 独立部分式 の特殊な場合を表現しています。

As an example where a possessive quantifier is suitable we consider matching a quoted string, as it appears in several programming languages. The backslash is used as an escape character that indicates that the next character is to be taken literally, as another character for the string. Therefore, after the opening quote, we expect a (possibly empty) sequence of alternatives: either some character except an unescaped quote or backslash or an escaped character.

絶対最大量指定子がふさわしい例として、いくつかのプログラミング言語で 現れるような、クォートされた文字列のマッチングを考えます。 バックスラッシュは次の文字が他の文字と同様リテラルに扱われることを示す エスケープ文字として使われます。 従って、開きクォートの後、選択肢の(空かもしれない)並びを想定します: エスケープされていないクォート文字以外の何らかの文字か、 バックスラッシュか、エスケープされた文字です。

    /"(?:[^"\\]++|\\.)*+"/;

正規表現を組み立てる

At this point, we have all the basic regexp concepts covered, so let's give a more involved example of a regular expression. We will build a regexp that matches numbers.

ここまでで、すべての基本的な正規表現のコンセプトをカバーしました; ですから、もっと複雑な正規表現に行ってみましょう。 例として、数値にマッチングする正規表現を組み立てます。

The first task in building a regexp is to decide what we want to match and what we want to exclude. In our case, we want to match both integers and floating point numbers and we want to reject any string that isn't a number.

正規表現を組み立てるにあたっての最初の仕事は何にマッチングさせるかと何を 排除するかを決めることです。 今回は、整数と浮動小数点数の両方にマッチングさせ、数値でない文字列をすべて 排除します。

The next task is to break the problem down into smaller problems that are easily converted into a regexp.

次の仕事は問題を、より正規表現に変換しやすい小さいな問題に 分解することです。

The simplest case is integers. These consist of a sequence of digits, with an optional sign in front. The digits we can represent with \d+ and the sign can be matched with [+-]. Thus the integer regexp is

もっとも簡単なケースは整数です。 これは数字の並びであり、省略可能な符号が先頭にあります。 数字は \d+ で表すことができ、符号は [+-] にマッチングさせることが できます。 したがって、整数にマッチングする正規表現は以下のようになります

    /[+-]?\d+/;  # matches integers

A floating point number potentially has a sign, an integral part, a decimal point, a fractional part, and an exponent. One or more of these parts is optional, so we need to check out the different possibilities. Floating point numbers which are in proper form include 123., 0.345, .34, -1e6, and 25.4E-72. As with integers, the sign out front is completely optional and can be matched by [+-]?. We can see that if there is no exponent, floating point numbers must have a decimal point, otherwise they are integers. We might be tempted to model these with \d*\.\d*, but this would also match just a single decimal point, which is not a number. So the three cases of floating point number without exponent are

浮動小数点数は符号と、整数部と、小数点と、小数部と、指数部を持つ可能性が あります。 これらの一つ以上のパーツが省略可能であり、可能なものをチェックする必要が あります。 正しい形式の浮動小数点数は123.、0.345、.34、-1e6、25.4E072 といったものを 含みます。 整数と同じように、先頭にある符合は省略可能で [+-]? にマッチングします。 もし指数部がないことがわかれば、浮動小数点数は小数点を持たなければならず、 これがない場合にはそれは整数です。 \d*\.\d* というパターンを使うことを思いつくかもしれませんが、これは 数値ではないただ一つの小数点にもマッチングしてしまいます。 ですから、指数部のない浮動小数点には以下の三つのケースが存在します

   /[+-]?\d+\./;  # 1., 321., etc.
   /[+-]?\.\d+/;  # .1, .234, etc.
   /[+-]?\d+\.\d+/;  # 1.0, 30.56, etc.

These can be combined into a single regexp with a three-way alternation:

これらは三つの選択を使った単一の正規表現にまとめることができます:

   /[+-]?(\d+\.\d+|\d+\.|\.\d+)/;  # floating point, no exponent

In this alternation, it is important to put '\d+\.\d+' before '\d+\.'. If '\d+\.' were first, the regexp would happily match that and ignore the fractional part of the number.

この選択肢において、'\d+\.\d+'が'\d+\.' より前に置かれていることが 重要です。 もし '\d+\.' が先頭にあったなら、この正規表現は数値の小数部を無視して マッチングしてしまうでしょう。

Now consider floating point numbers with exponents. The key observation here is that both integers and numbers with decimal points are allowed in front of an exponent. Then exponents, like the overall sign, are independent of whether we are matching numbers with or without decimal points, and can be "decoupled" from the mantissa. The overall form of the regexp now becomes clear:

ここで指数部を持つ浮動小数点数を考えてみましょう。 ここでのポイントは指数部の前に整数と小数点を伴った数の 両方 が 現れることができるということです。 指数部は符号と同じように、小数点を伴うか伴わないかに関係なくマッチングし、 仮数部から「分離」することも可能です。 正規表現の全体の形式がこれで明らかになりました:

    /^(optional sign)(integer | f.p. mantissa)(optional exponent)$/;

The exponent is an 'e' or 'E', followed by an integer. So the exponent regexp is

指数部は整数が続く 'e' もしくは 'E' です。 ですから指数部の正規表現は以下のようになります

   /[eE][+-]?\d+/;  # exponent

Putting all the parts together, we get a regexp that matches numbers:

すべてのパーツを一つにまとめることによって、数値にマッチングする正規表現を 手に入れます:

   /^[+-]?(\d+\.\d+|\d+\.|\.\d+|\d+)([eE][+-]?\d+)?$/;  # Ta da!

Long regexps like this may impress your friends, but can be hard to decipher. In complex situations like this, the /x modifier for a match is invaluable. It allows one to put nearly arbitrary whitespace and comments into a regexp without affecting their meaning. Using it, we can rewrite our "extended" regexp in the more pleasing form

このような長い正規表現を友人に説明することがあるかもしれませんが、 解読するのが難しいかもしれません。 このような複雑なものにおいては、/x 修飾子は重要なものです。 この修飾子は正規表現に対してその意味を変えることなく、ほぼ任意の空白を 入れたりコメントを入れたりすることを許します。 これを使うことによって、よりわかりやすい形式に正規表現を 「拡張」することができます

   /^
      [+-]?         # first, match an optional sign
      (             # then match integers or f.p. mantissas:
          \d+\.\d+  # mantissa of the form a.b
         |\d+\.     # mantissa of the form a.
         |\.\d+     # mantissa of the form .b
         |\d+       # integer of the form a
      )
      ( [eE] [+-]? \d+ )?  # finally, optionally match an exponent
   $/x;
   /^
      [+-]?         # まずはじめに、省略可能な符号にマッチング
      (             # 続いて整数か f.p. 仮数部にマッチング:
          \d+\.\d+  # a.b 形式の仮数部
         |\d+\.     # a. 形式の仮数部
         |\.\d+     # .b 形式の仮数部
         |\d+       # a 形式の整数
      )
      ( [eE] [+-]? \d+ )?  # 最後に、省略可能な指数部にマッチング
   $/x;

If whitespace is mostly irrelevant, how does one include space characters in an extended regexp? The answer is to backslash it '\ ' or put it in a character class [ ]. The same thing goes for pound signs: use \# or [#]. For instance, Perl allows a space between the sign and the mantissa or integer, and we could add this to our regexp as follows:

もし空白が余計なものであれば、拡張された正規表現にスペースを含ませるには どうすればよいのでしょうか? その答えは '\ ' のように バックスラッシュを前置するか、[ ] のように文字クラスに 押し込めることです。 同じことが '#' にも言えます: \#[#] を使います。 たとえば、Perl が符号と仮数部(もしくは整数部) の間に空白を置くことを 許すとすると、以下のように正規表現に加えることができます:

   /^
      [+-]?\ *      # first, match an optional sign *and space*
      (             # then match integers or f.p. mantissas:
          \d+\.\d+  # mantissa of the form a.b
         |\d+\.     # mantissa of the form a.
         |\.\d+     # mantissa of the form .b
         |\d+       # integer of the form a
      )
      ( [eE] [+-]? \d+ )?  # finally, optionally match an exponent
   $/x;
   /^
      [+-]?\ *      # まずはじめに、省略可能な符号と*スペース*にマッチング
      (             # 続いて整数か f.p. 仮数部にマッチング:
          \d+\.\d+  # a.b 形式の仮数部
         |\d+\.     # a. 形式の仮数部
         |\.\d+     # .b 形式の仮数部
         |\d+       # a 形式の整数
      )
      ( [eE] [+-]? \d+ )?  # 最後に、省略可能な指数部にマッチング
   $/x;

In this form, it is easier to see a way to simplify the alternation. Alternatives 1, 2, and 4 all start with \d+, so it could be factored out:

この形式においては、選択肢を単純にする方法を見つけるのは簡単です。 選択肢 1, 2, 4 はすべて \d+ で始まっています; ですからこれは まとめることができます:

   /^
      [+-]?\ *      # first, match an optional sign
      (             # then match integers or f.p. mantissas:
          \d+       # start out with a ...
          (
              \.\d* # mantissa of the form a.b or a.
          )?        # ? takes care of integers of the form a
         |\.\d+     # mantissa of the form .b
      )
      ( [eE] [+-]? \d+ )?  # finally, optionally match an exponent
   $/x;
   /^
      [+-]?\ *      # まずはじめに、省略可能な符号にマッチング
      (             # 続いて整数か f.p. 仮数部にマッチング:
          \d+       # はじめは…
          (
              \.\d* # a.b形式もしくはa.形式の仮数部
          )?        # ? はa形式の整数を考慮する
         |\.\d+     # .b形式の仮数部
      )
      ( [eE] [+-]? \d+ )?  # 最後に、省略可能な指数部にマッチング
   $/x;

Starting in Perl v5.26, specifying /xx changes the square-bracketed portions of a pattern to ignore tabs and space characters unless they are escaped by preceding them with a backslash. So, we could write

Perl v5.26 から、/xx を指定すると、逆スラッシュを前置することによって エスケープしない限り、タブとスペースの文字をを無視するように パターンの大かっこで囲まれた部分を変更します。 従って、次のように書けます:

   /^
      [ + - ]?\ *   # first, match an optional sign
      (             # then match integers or f.p. mantissas:
          \d+       # start out with a ...
          (
              \.\d* # mantissa of the form a.b or a.
          )?        # ? takes care of integers of the form a
         |\.\d+     # mantissa of the form .b
      )
      ( [ e E ] [ + - ]? \d+ )?  # finally, optionally match an exponent
   $/xx;

This doesn't really improve the legibility of this example, but it's available in case you want it. Squashing the pattern down to the compact form, we have

これはこの例の読みやすさを本当に改善してはいませんが、 使いたい場所では利用可能です。 コンパクトな型式にパターンを圧縮すると、次のようになります:

    /^[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;

This is our final regexp. To recap, we built a regexp by

これが最終形の正規表現です。 ここでは以下のようにして正規表現を組み立てました。

  • specifying the task in detail,

    なすべきことを詳細に確定し、

  • breaking down the problem into smaller parts,

    問題を小さなパーツに分割し、

  • translating the small parts into regexps,

    その小さなパーツを正規表現に変換し、

  • combining the regexps,

    その正規表現を組み合わせ、

  • and optimizing the final combined regexp.

    組み合わされた最終的な正規表現を最適化する。

These are also the typical steps involved in writing a computer program. This makes perfect sense, because regular expressions are essentially programs written in a little computer language that specifies patterns.

これはコンピュータプログラムを書くにあたっての典型的なステップでも あります。 正規表現はパターンを特定する小さなコンピュータ言語で書く プログラムであるので、このことはまさに当てはまります。

Perl で正規表現を使う

The last topic of Part 1 briefly covers how regexps are used in Perl programs. Where do they fit into Perl syntax?

パート 1 の最後のトピックは正規表現がPerlプログラムでどのように 使われているかを説明します。 正規表現は Perl の構文のどこにフィットしているのでしょう?

We have already introduced the matching operator in its default /regexp/ and arbitrary delimiter m!regexp! forms. We have used the binding operator =~ and its negation !~ to test for string matches. Associated with the matching operator, we have discussed the single line /s, multi-line /m, case-insensitive /i and extended /x modifiers. There are a few more things you might want to know about matching operators.

すでにデフォルトの /regexp/ と任意のデリミタを持つ m!regexp! 形式の マッチング演算子を説明しています。 マッチングさせる文字列を指定するために =~ 演算子や !~ 演算子を 使っています。 マッチング演算子について、単一行修飾子 /s、複数行修飾子 /m、 大小文字の違いを無視する修飾子 /i、拡張修飾子 /x について述べました。 マッチング演算子に関して、知っておきたいであろういくつかの事柄があります。

置換を禁止する

If you change $pattern after the first substitution happens, Perl will ignore it. If you don't want any substitutions at all, use the special delimiter m'':

もし最初の置換が行われた後で $pattern を変更したとしても、Perl は それを無視します。 すべての置換を行いたくないというのであれば、特殊なデリミタ m'' を使います:

    @pattern = ('Seuss');
    while (<>) {
        print if m'@pattern';  # matches literal '@pattern', not 'Seuss'
    }
    @pattern = ('Seuss');
    while (<>) {
        print if m'@pattern';  # 'Seuss' ではなくリテラルの '@pattern' にマッチング
    }

Similar to strings, m'' acts like apostrophes on a regexp; all other 'm' delimiters act like quotes. If the regexp evaluates to the empty string, the regexp in the last successful match is used instead. So we have

文字列と同様、m'' は正規表現においてシングルクォートのように振舞います。 他のすべての 'm' デリミタはダブルクォートのように振舞います。 もし正規表現が空文字列を評価したならば、その正規表現は 最後に成功した マッチングにある正規表現が代わりに使われます。

    "dog" =~ /d/;  # 'd' matches
    "dogbert" =~ //;  # this matches the 'd' regexp used before
    "dog" =~ /d/;  # 'd' にマッチング
    "dogbert" =~ //;  # 直前に使われた正規表現である 'd' にマッチング

グローバルマッチング

The final two modifiers we will discuss here, /g and /c, concern multiple matches. The modifier /g stands for global matching and allows the matching operator to match within a string as many times as possible. In scalar context, successive invocations against a string will have /g jump from match to match, keeping track of position in the string as it goes along. You can get or set the position with the pos() function.

ここで議論する最後の二つの修飾子 /g/c は複数回マッチングに 関連するものです。 修飾子 /g はグローバルマッチングを意味し、マッチング演算子に対して 文字列の中で可能な限りの回数マッチングするようにします。 スカラコンテキストでは、ある文字列に対する連続した呼び出しはマッチングから マッチングへとジャンプする /g を持ち、その文字列の中での位置を記憶します。 pos() 関数を使ってこの位置を取り出したり設定したりすることができます。

The use of /g is shown in the following example. Suppose we have a string that consists of words separated by spaces. If we know how many words there are in advance, we could extract the words using groupings:

/g を使った例を以下に挙げます。 ここで、空白によって区切られた単語の並びからなる文字列があるとします。 もしいくつの単語があるかがわかっていれば、グループ化を使って単語を 取り出すことができます:

    $x = "cat dog house"; # 3 words
    $x =~ /^\s*(\w+)\s+(\w+)\s+(\w+)\s*$/; # matches,
                                           # $1 = 'cat'
                                           # $2 = 'dog'
                                           # $3 = 'house'

But what if we had an indeterminate number of words? This is the sort of task /g was made for. To extract all words, form the simple regexp (\w+) and loop over all matches with /(\w+)/g:

しかしもし不定個の単語があるとしたら? これが /g が作られた理由となった類の仕事です。 すべての単語を取り出すために、単純な (\w+) という正規表現を使い、 /(\w+)/g をループで使ってすべてにマッチングさせます:

    while ($x =~ /(\w+)/g) {
        print "Word is $1, ends at position ", pos $x, "\n";
    }

prints

以下の出力を行います

    Word is cat, ends at position 3
    Word is dog, ends at position 7
    Word is house, ends at position 13

A failed match or changing the target string resets the position. If you don't want the position reset after failure to match, add the /c, as in /regexp/gc. The current position in the string is associated with the string, not the regexp. This means that different strings have different positions and their respective positions can be set or read independently.

マッチングに失敗したり、ターゲット文字列を変更するとこの位置は リセットされます。 もしマッチングに失敗したときに位置をリセットしたくないのであれば、 /regexp/gc のように /c を追加します。 文字列の中のカレント位置はその文字列に結び付けられていて、正規表現にでは ありません。 このことは異なる文字列は異なる位置を持っていて、それらのそれぞれの位置は 独立にセットしたり読み出したりすることが可能です。

In list context, /g returns a list of matched groupings, or if there are no groupings, a list of matches to the whole regexp. So if we wanted just the words, we could use

リストコンテキストでは、/g はマッチングしたグループのリストを返します; グループ化の指定がなければ、正規表現全体にマッチングするリストを返します。 ですから、単に単語が欲しいのでれば

    @words = ($x =~ /(\w+)/g);  # matches,
                                # $words[0] = 'cat'
                                # $words[1] = 'dog'
                                # $words[2] = 'house'

Closely associated with the /g modifier is the \G anchor. The \G anchor matches at the point where the previous /g match left off. \G allows us to easily do context-sensitive matching:

/g 修飾子は\Gアンカーに強く結び付けられています。 \G アンカーは直前の /g マッチングで残った部分にマッチングします。 \G はコンテキストを考慮したマッチング(context-sensitive matching)を 容易にさせます:

    $metric = 1;  # use metric units
    ...
    $x = <FILE>;  # read in measurement
    $x =~ /^([+-]?\d+)\s*/g;  # get magnitude
    $weight = $1;
    if ($metric) { # error checking
        print "Units error!" unless $x =~ /\Gkg\./g;
    }
    else {
        print "Units error!" unless $x =~ /\Glbs\./g;
    }
    $x =~ /\G\s+(widget|sprocket)/g;  # continue processing
    $metric = 1;  # metric ユニットを使う
    ...
    $x = <FILE>;  # 測定のために読み込み
    $x =~ /^([+-]?\d+)\s*/g;  # 重さを取得
    $weight = $1;
    if ($metric) { # エラーチェック
        print "Units error!" unless $x =~ /\Gkg\./g;
    }
    else {
        print "Units error!" unless $x =~ /\Glbs\./g;
    }
    $x =~ /\G\s+(widget|sprocket)/g;  # 処理を続ける

The combination of /g and \G allows us to process the string a bit at a time and use arbitrary Perl logic to decide what to do next. Currently, the \G anchor is only fully supported when used to anchor to the start of the pattern.

/g\G の組み合わせは一度に文字列を少しだけ処理して、次に 行うことを決定するために任意の Perl のロジックを使うことを可能にします。 現在のところ、\G アンカーはパターンの最初に使われたときのみ 完全にサポートされます。

\G is also invaluable in processing fixed-length records with regexps. Suppose we have a snippet of coding region DNA, encoded as base pair letters ATCGTTGAAT... and we want to find all the stop codons TGA. In a coding region, codons are 3-letter sequences, so we can think of the DNA snippet as a sequence of 3-letter records. The naive regexp

\G はまた、正規表現を使って固定長のレコードを処理するときに貴重なものです。 基礎となる組み合わせ文字でエンコードされた ATCGTTGAAT... のような DNA の符号化部分があるとして、すべてのストップコドン (codon: 3 つの ヌクレオチドから成る,遺伝情報の単位)を見つけ出したいとしましょう。 符号化部分の中では、コドンは三文字の並びなので DNA の断片を 三文字のレコードの並びとしてみなすことができます。 単純な正規表現である

    # expanded, this is "ATC GTT GAA TGC AAA TGA CAT GAC"
    $dna = "ATCGTTGAATGCAAATGACATGAC";
    $dna =~ /TGA/;

doesn't work; it may match a TGA, but there is no guarantee that the match is aligned with codon boundaries, e.g., the substring GTT GAA gives a match. A better solution is

はうまくいきません; これは TGA にマッチングはしますが、 GTT GAA のようにコドンの境界にないものにもマッチングしてしまいます。 より良い解決策は以下のようなものです

    while ($dna =~ /(\w\w\w)*?TGA/g) {  # note the minimal *?
        print "Got a TGA stop codon at position ", pos $dna, "\n";
    }

which prints

これは以下を出力します

    Got a TGA stop codon at position 18
    Got a TGA stop codon at position 23

Position 18 is good, but position 23 is bogus. What happened?

Position 18 は良いですが、23 は変です。 何が起きているのでしょう?

The answer is that our regexp works well until we get past the last real match. Then the regexp will fail to match a synchronized TGA and start stepping ahead one character position at a time, not what we want. The solution is to use \G to anchor the match to the codon alignment:

その答えは、私たちの正規表現が最後に本当にマッチングしたところまでは うまくいっているからです。 それからこの正規表現は TGA の同期に失敗して私たちが望んでいない場所から マッチングのステップを始めてしまうのです。 解決策は、コドンの境界にマッチングさせるために \G を 使って印付けをすることです:

    while ($dna =~ /\G(\w\w\w)*?TGA/g) {
        print "Got a TGA stop codon at position ", pos $dna, "\n";
    }

This prints

これは次を出力します:

    Got a TGA stop codon at position 18

which is the correct answer. This example illustrates that it is important not only to match what is desired, but to reject what is not desired.

そして正しい答えです。 この例はマッチングしたものにマッチングすることだけが重要なのではなく、 望んでいないものを排除することもまたそうなのだということを 明らかにしました。

(There are other regexp modifiers that are available, such as /o, but their specialized uses are beyond the scope of this introduction. )

(/o のようなその他の正規表現修飾子も利用可能ですが、これらの特殊な 使用法はこの序論のスコープからは外れます。)

検索と置換

Regular expressions also play a big role in search and replace operations in Perl. Search and replace is accomplished with the s/// operator. The general form is s/regexp/replacement/modifiers, with everything we know about regexps and modifiers applying in this case as well. The replacement is a Perl double-quoted string that replaces in the string whatever is matched with the regexp. The operator =~ is also used here to associate a string with s///. If matching against $_, the $_ =~ can be dropped. If there is a match, s/// returns the number of substitutions made; otherwise it returns false. Here are a few examples:

正規表現はまた、Perl における検索と置換操作において大きな役割を 果たしています。 検索と置換は s/// 演算子に結び付けられています。 一般的な形は s/regexp/replacement/modifiers で、知っているすべての 正規表現と修飾子をここで使うことができます。 replacement は Perlでのダブルクォートで囲まれた文字列で、 regexp にマッチングした文字列を置き換えるものです。 =~ 演算子もまた s/// を伴った文字列に結びつけられるために使われます。 $_ に対してマッチングを行う場合には、$_ =~ は省略できます。 マッチングに成功した場合には s/// は置換が行われた数を返します; 失敗した場合には偽を返します。 幾つか例を挙げましょう:

    $x = "Time to feed the cat!";
    $x =~ s/cat/hacker/;   # $x contains "Time to feed the hacker!"
    if ($x =~ s/^(Time.*hacker)!$/$1 now!/) {
        $more_insistent = 1;
    }
    $y = "'quoted words'";
    $y =~ s/^'(.*)'$/$1/;  # strip single quotes,
                           # $y contains "quoted words"
    $x = "Time to feed the cat!";
    $x =~ s/cat/hacker/;   # $x の内容は "Time to feed the hacker!"
    if ($x =~ s/^(Time.*hacker)!$/$1 now!/) {
        $more_insistent = 1;
    }
    $y = "'quoted words'";
    $y =~ s/^'(.*)'$/$1/;  # シングルクォートを剥ぎ取る
                           # $y の内容は "quoted words"

In the last example, the whole string was matched, but only the part inside the single quotes was grouped. With the s/// operator, the matched variables $1, $2, etc. are immediately available for use in the replacement expression, so we use $1 to replace the quoted string with just what was quoted. With the global modifier, s///g will search and replace all occurrences of the regexp in the string:

最後の例では、文字列全体がマッチングしますが、シングルクォートの内部の 部分のみがグループ化されます。 s/// 演算子では、マッチングした変数 $1, $2, などは置換式で 使えるように直ちに利用可能になるので、クォートされた文字列を中身で 置換するために $1 を使います。 グローバル修飾子付きなので、s///g は文字列中の全てを検索して置換します:

    $x = "I batted 4 for 4";
    $x =~ s/4/four/;   # doesn't do it all:
                       # $x contains "I batted four for 4"
    $x = "I batted 4 for 4";
    $x =~ s/4/four/g;  # does it all:
                       # $x contains "I batted four for four"
    $x = "I batted 4 for 4";
    $x =~ s/4/four/;   # すべてにはマッチングしない:
                       # $x の内容は "I batted four for 4"
    $x = "I batted 4 for 4";
    $x =~ s/4/four/g;  # すべてにマッチング:
                       # $x の内容は "I batted four for four"

If you prefer "regex" over "regexp" in this tutorial, you could use the following program to replace it:

このチュートリアルにある "regexp" を "regex" にすることを望むのなら、 以下のプログラムを使って置換することができます:

    % cat > simple_replace
    #!/usr/bin/perl
    $regexp = shift;
    $replacement = shift;
    while (<>) {
        s/$regexp/$replacement/g;
        print;
    }
    ^D

    % simple_replace regexp regex perlretut.pod

In simple_replace we used the s///g modifier to replace all occurrences of the regexp on each line. (Even though the regular expression appears in a loop, Perl is smart enough to compile it only once.) As with simple_grep, both the print and the s/$regexp/$replacement/g use $_ implicitly.

simple_replace では各行のすべての正規表現にマッチングする部分を 置換するために s///g 修飾子を使います。 (正規表現がループ中にあるように見えますが、Perl はこれを一度だけ コンパイルするぐらい賢いです。) simple_grep と同様、prints/$regexp/$replacement/g$_ を暗黙に使用しています。

If you don't want s/// to change your original variable you can use the non-destructive substitute modifier, s///r. This changes the behavior so that s///r returns the final substituted string (instead of the number of substitutions):

基の変数を変更するために s/// を使いたくないなら、非破壊置換修飾子である s///r が使えます。 これは、s///r が (置換の数ではなく)最終的に置換された文字列を返すように 振る舞いを変更します:

    $x = "I like dogs.";
    $y = $x =~ s/dogs/cats/r;
    print "$x $y\n";

That example will print "I like dogs. I like cats". Notice the original $x variable has not been affected. The overall result of the substitution is instead stored in $y. If the substitution doesn't affect anything then the original string is returned:

この例は、"I like dogs. I like cats" を表示します。 元の $x 変数は影響を受けないことに注意してください。 置換の結果全体は代わりに $y に格納されます。 置換が何も影響を与えなかった場合、元の文字列が返されます:

    $x = "I like dogs.";
    $y = $x =~ s/elephants/cougars/r;
    print "$x $y\n"; # prints "I like dogs. I like dogs."

One other interesting thing that the s///r flag allows is chaining substitutions:

s///r フラグによるもう一つの興味深いことは、置換の連鎖です:

    $x = "Cats are great.";
    print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~
        s/Frogs/Hedgehogs/r, "\n";
    # prints "Hedgehogs are great."

A modifier available specifically to search and replace is the s///e evaluation modifier. s///e treats the replacement text as Perl code, rather than a double-quoted string. The value that the code returns is substituted for the matched substring. s///e is useful if you need to do a bit of computation in the process of replacing text. This example counts character frequencies in a line:

検索と置換において使うことのできる修飾子に評価修飾子 s///e があります。 s///e は、置換文字列をダブルクォートされた文字列ではなく Perl コードとして扱います。 コードが返した値はマッチングした部分文字列と置換されます。 s///e は置換テキストの処理においてちょっとした計算を行う必要が あるときに便利です。 以下の例はある行の文字の出現頻度を数えます:

    $x = "Bill the cat";
    $x =~ s/(.)/$chars{$1}++;$1/eg; # final $1 replaces char with itself
    print "frequency of '$_' is $chars{$_}\n"
        foreach (sort {$chars{$b} <=> $chars{$a}} keys %chars);
    $x = "Bill the cat";
    $x =~ s/(.)/$chars{$1}++;$1/eg; # 最終的に $1 はそれ自身の文字に置換される
    print "frequency of '$_' is $chars{$_}\n"
        foreach (sort {$chars{$b} <=> $chars{$a}} keys %chars);

This prints

これは次を出力します:

    frequency of ' ' is 2
    frequency of 't' is 2
    frequency of 'l' is 2
    frequency of 'B' is 1
    frequency of 'c' is 1
    frequency of 'e' is 1
    frequency of 'h' is 1
    frequency of 'i' is 1
    frequency of 'a' is 1

As with the match m// operator, s/// can use other delimiters, such as s!!! and s{}{}, and even s{}//. If single quotes are used s''', then the regexp and replacement are treated as single-quoted strings and there are no variable substitutions. s/// in list context returns the same thing as in scalar context, i.e., the number of matches.

m// 演算子と同様に、s///s!!!s{}{} 、 果ては s{}// のように異なるデリミタを使うことができます。 s''' のようにシングルクォートが使われた場合、その正規表現と 置換テキストはシングルクォート文字列のように扱われ、変数の置き換えは 行われません。 リストコンテキストでの s/// はスカラコンテキストのときと同じように、 マッチングした数を返します。

split 関数

The split() function is another place where a regexp is used. split /regexp/, string, limit separates the string operand into a list of substrings and returns that list. The regexp must be designed to match whatever constitutes the separators for the desired substrings. The limit, if present, constrains splitting into no more than limit number of strings. For example, to split a string into words, use

split() 関数は、正規表現が使えるもう一つの場所です。 split /regexp/, string, limitstring オペランドを部分文字列の リストに分割し、そのリストを返します。 正規表現は、目的の部分文字列のセパレータを構成するものに マッチングするようにしなければなりません。 limit が与えられた場合には、文字列を limit 個を超える数には 分割しません。 たとえば、文字列を単語に分割するには以下のようにします

    $x = "Calvin and Hobbes";
    @words = split /\s+/, $x;  # $word[0] = 'Calvin'
                               # $word[1] = 'and'
                               # $word[2] = 'Hobbes'

If the empty regexp // is used, the regexp always matches and the string is split into individual characters. If the regexp has groupings, then the resulting list contains the matched substrings from the groupings as well. For instance,

// が使われた場合には、その正規表現は常にマッチングし、文字列は個々の文字に 分割されます。 正規表現がグループ化を伴っていた場合には、グループ化されたものも部分文字列に 含まれるようになります。 たとえば:

    $x = "/usr/bin/perl";
    @dirs = split m!/!, $x;  # $dirs[0] = ''
                             # $dirs[1] = 'usr'
                             # $dirs[2] = 'bin'
                             # $dirs[3] = 'perl'
    @parts = split m!(/)!, $x;  # $parts[0] = ''
                                # $parts[1] = '/'
                                # $parts[2] = 'usr'
                                # $parts[3] = '/'
                                # $parts[4] = 'bin'
                                # $parts[5] = '/'
                                # $parts[6] = 'perl'

Since the first character of $x matched the regexp, split prepended an empty initial element to the list.

$x の最初の文字に正規表現がマッチングしているので、split はリストの 最初の要素に空要素を置きます。

If you have read this far, congratulations! You now have all the basic tools needed to use regular expressions to solve a wide range of text processing problems. If this is your first time through the tutorial, why not stop here and play around with regexps a while.... Part 2 concerns the more esoteric aspects of regular expressions and those concepts certainly aren't needed right at the start.

ここまで読み進めてきたのならおめでとう! あなたは広範囲のテキスト処理を解決するのに必要な正規表現の基本的な部分を すべて会得しました。 このチュートリアルを初めて読んでここまできたのなら、ここで立ち止まって 正規表現を使ってみるのも良いでしょう。 Part 2 ではより難解な正規表現の側面に言及します。

パート 2: 強力なツール

OK, you know the basics of regexps and you want to know more. If matching regular expressions is analogous to a walk in the woods, then the tools discussed in Part 1 are analogous to topo maps and a compass, basic tools we use all the time. Most of the tools in part 2 are analogous to flare guns and satellite phones. They aren't used too often on a hike, but when we are stuck, they can be invaluable.

あなたはすでに正規表現の基本的なことを知っていて、より深く 知ろうとしています。 正規表現のマッチングが森の中を歩くことに類似しているのなら、パート 1 で 述べられたツールは地図でありコンパスであり、いつも使う基本的な道具です。 パート 2 での大部分のツールは照明弾であり、衛星電話です。 ハイキングにはそうそう使うものではありませんが、困り果てたときには とても貴重なものです。

What follows are the more advanced, less used, or sometimes esoteric capabilities of Perl regexps. In Part 2, we will assume you are comfortable with the basics and concentrate on the advanced features.

以下に挙げるものは Perl の正規表現においてより高度で、 あまり使うことのない、時として難解な機能です。 Part 2 では、あなたが基本を良く知っていてより進んだ機能に集中できることを 仮定しています。

文字、文字列、文字クラスについての追加事項

There are a number of escape sequences and character classes that we haven't covered yet.

まだカバーしていない幾つかのエスケープシーケンスや文字クラスがあります。

There are several escape sequences that convert characters or strings between upper and lower case, and they are also available within patterns. \l and \u convert the next character to lower or upper case, respectively:

文字や文字列の大小文字を変換するエスケープシーケンスがあり、 これらもパターンで使えます。 \l\u は続く文字をそれぞれ小文字と大文字に変換します:

    $x = "perl";
    $string =~ /\u$x/;  # matches 'Perl' in $string
    $x = "M(rs?|s)\\."; # note the double backslash
    $string =~ /\l$x/;  # matches 'mr.', 'mrs.', and 'ms.',
    $x = "perl";
    $string =~ /\u$x/;  # $string の中の 'Perl' にマッチング
    $x = "M(rs?|s)\\."; # 二重のバックスラッシュに注意
    $string =~ /\l$x/;  # 'mr.', 'mrs.', 'ms.' にマッチング

A \L or \U indicates a lasting conversion of case, until terminated by \E or thrown over by another \U or \L:

\L\U は、\E で終端されるか、別の \U\L で 上書きされるまで、大文字小文字を変換することを示します:

    $x = "This word is in lower case:\L SHOUT\E";
    $x =~ /shout/;       # matches
    $x = "I STILL KEYPUNCH CARDS FOR MY 360";
    $x =~ /\Ukeypunch/;  # matches punch card string
    $x = "This word is in lower case:\L SHOUT\E";
    $x =~ /shout/;       # マッチングする
    $x = "I STILL KEYPUNCH CARDS FOR MY 360";
    $x =~ /\Ukeypunch/;  # パンチカード文字列にマッチングする

If there is no \E, case is converted until the end of the string. The regexps \L\u$word or \u\L$word convert the first character of $word to uppercase and the rest of the characters to lowercase. (Beyond ASCII characters, it gets somewhat more complicated; \u actually performs titlecase mapping, which for most characters is the same as uppercase, but not for all; see https://unicode.org/faq/casemap_charprop.html#4.)

\E がない場合には、大小文字の変換は文字列の終端まで行われます。 \L\u$word\u\L$word$word の最初の文字を大文字へと変換し、 残りの文字は小文字にします。 (ASCII を超えた文字では、もう少し複雑です; \u は実際には タイトル文字 マッピングを実行します; ほとんどの文字に対してはこれは大文字と同じですが、全てではありません; https://unicode.org/faq/casemap_charprop.html#4 を参照してください。)

Control characters can be escaped with \c, so that a control-Z character would be matched with \cZ. The escape sequence \Q...\E quotes, or protects most non-alphabetic characters. For instance,

制御文字は \c を使ってエスケープすることができます; ですから、 control-Z 文字は \cZ にマッチングします。 \Q...\E というエスケープシーケンスは大部分の非アルファベット文字を クォートまたはプロテクトします。 たとえば:

    $x = "\QThat !^*&%~& cat!";
    $x =~ /\Q!^*&%~&\E/;  # check for rough language

It does not protect '$' or '@', so that variables can still be substituted.

これは '$''@' を保護しないので、変数の置換は行われます。

\Q, \L, \l, \U, \u and \E are actually part of double-quotish syntax, and not part of regexp syntax proper. They will work if they appear in a regular expression embedded directly in a program, but not when contained in a string that is interpolated in a pattern.

\Q, \L, \l, \U, \u, \E は実際にはダブルクォート風文法の 一部で、正規表現文法の一部ではありません。 これらはプログラム中の正規表現に直接埋め込まれている場合は動作しますが、 パターン内で展開された文字列に含まれている場合には動作しません。

Perl regexps can handle more than just the standard ASCII character set. Perl supports Unicode, a standard for representing the alphabets from virtually all of the world's written languages, and a host of symbols. Perl's text strings are Unicode strings, so they can contain characters with a value (codepoint or character number) higher than 255.

Perl の正規表現は標準の ASCII 文字セットを超えた扱いをすることができます。 Perl は現在は事実上世界の全ての言語のアルファベットを表現する標準である Unicode をサポートしています。 Perl のテキスト文字列は Unicode 文字列で、255 以上の値(コードポイントまたは 文字番号)を持つ文字を含みます。

What does this mean for regexps? Well, regexp users don't need to know much about Perl's internal representation of strings. But they do need to know 1) how to represent Unicode characters in a regexp and 2) that a matching operation will treat the string to be searched as a sequence of characters, not bytes. The answer to 1) is that Unicode characters greater than chr(255) are represented using the \x{hex} notation, because \xXY (without curly braces and XY are two hex digits) doesn't go further than 255. (Starting in Perl 5.14, if you're an octal fan, you can also use \o{oct}.)

このことが正規表現に及ぼす影響は? そう、正規表現ユーザーは perl での文字列の内部表現を知る必要はありません。 しかし、知っておくべきことがあります; 1) 正規表現において Unicode 文字をどのように表現するか 2) マッチング操作がバイト列ではなく、Unicode 文字列として扱うということです。 1)に対する答えは chr(255) を越える Unicode 文字は \x{hex} 表記を 使って表現されるだろうということです; なぜなら、\xXY 表記(中かっこなしで XY は二つの 16 進数) は 255 を 超えないからです。 (Perl 5.14 から、8 進数が好みなら、\o{oct} も使えます。)

    /\x{263a}/;   # match a Unicode smiley face :)
    /\x{ 263a }/; # Same

NOTE: In Perl 5.6.0 it used to be that one needed to say use utf8 to use any Unicode features. This is no longer the case: for almost all Unicode processing, the explicit utf8 pragma is not needed. (The only case where it matters is if your Perl script is in Unicode and encoded in UTF-8, then an explicit use utf8 is needed.)

注意: Perl 5.6.0 では何かしらの Unicode 機構を使うときには use utf8 を 宣言する必要がありました。 これはもはやあてはまりません: ほとんどすべての Unicode 処理においては、 utf8 プラグマは必要ありません。 (これが意味を持つただ一つのケースは、 あなたの Perl スクリプトが Unicode で書かれていて、かつそれが UTF-8 で エンコーディングされている場合で、このときは陽に use utf8 を指定する必要があります。)

Figuring out the hexadecimal sequence of a Unicode character you want or deciphering someone else's hexadecimal Unicode regexp is about as much fun as programming in machine code. So another way to specify Unicode characters is to use the named character escape sequence \N{name}. name is a name for the Unicode character, as specified in the Unicode standard. For instance, if we wanted to represent or match the astrological sign for the planet Mercury, we could use

あなたが必要な Unicode 文字を 16 進数で表記することや、別の誰かが 16 進表記の Unicode 正規表現を解読することは、機械語で プログラミングすることを楽しむかのようです。 ですから、Unicode 文字を指定する別の方法として \N{name} のような 名前付き文字 エスケープシーケンスを使うものがあります。 name は Unicode 文字に対する名前であって、Unicode standard で 定義されているものです。 たとえば、水星を表す占星術記号を表したりマッチングさせるために 以下のようにします

    $x = "abc\N{MERCURY}def";
    $x =~ /\N{MERCURY}/;   # matches
    $x =~ /\N{ MERCURY }/; # Also matches
    $x = "abc\N{MERCURY}def";
    $x =~ /\N{MERCURY}/;   # マッチング
    $x =~ /\N{ MERCURY }/; # これもマッチング

One can also use "short" names:

「短い」名前を使うこともできます:

    print "\N{GREEK SMALL LETTER SIGMA} is called sigma.\n";
    print "\N{greek:Sigma} is an upper-case sigma.\n";

You can also restrict names to a certain alphabet by specifying the charnames pragma:

charnames プラグマを指定することで名前を特定のアルファベットに 制限することもできます:

    use charnames qw(greek);
    print "\N{sigma} is Greek sigma\n";

An index of character names is available on-line from the Unicode Consortium, https://www.unicode.org/charts/charindex.html; explanatory material with links to other resources at https://www.unicode.org/standard/where.

文字名の一覧は Unicode Consortium の https://www.unicode.org/charts/charindex.html からオンラインで 利用可能です; その他のリソースへのリンクを含む説明に関する情報は https://www.unicode.org/standard/where にあります。

Starting in Perl v5.32, an alternative to \N{...} for full names is available, and that is to say

Perl v5.32 から、完全名の \N{...} の代替策が利用可能で、 それは次のようにすることです:

 /\p{Name=greek small letter sigma}/

The casing of the character name is irrelevant when used in \p{}, as are most spaces, underscores and hyphens. (A few outlier characters cause problems with ignoring all of them always. The details (which you can look up when you get more proficient, and if ever needed) are in https://www.unicode.org/reports/tr44/tr44-24.html#UAX44-LM2).

文字名の大文字小文字は、\p{} で使われるときは、ほとんどの空白や 下線、ハイフンと同様、無関係です。 (これらの全てを常に無視すると一部の特殊な文字で問題が起きます。 (より熟練して調べられるようになり、必要になった場合のための) 詳細は https://www.unicode.org/reports/tr44/tr44-24.html#UAX44-LM2 に あります)。

The answer to requirement 2) is that a regexp (mostly) uses Unicode characters. The "mostly" is for messy backward compatibility reasons, but starting in Perl 5.14, any regexp compiled in the scope of a use feature 'unicode_strings' (which is automatically turned on within the scope of a use v5.12 or higher) will turn that "mostly" into "always". If you want to handle Unicode properly, you should ensure that 'unicode_strings' is turned on. Internally, this is encoded to bytes using either UTF-8 or a native 8 bit encoding, depending on the history of the string, but conceptually it is a sequence of characters, not bytes. See perlunitut for a tutorial about that.

2) の答えは、正規表現は(ほとんど) Unicode 文字を使うというものです。 「ほとんど」というのはぐちゃぐちゃな後方互換性の理由ですが、 Perl 5.14 から、use feature 'unicode_strings' (これは use 5.012 以上が 有効なスコープ内では自動的にオンになります) によって「ほとんど」は「常に」に なります。 Unicode を適切に扱いたいなら、'unicode_strings' をオンに するようにするべきです。 内部では、これは UTF-8 かネイティブな 8 ビットエンコーディングを使った バイトでエンコードされてます; どちらかは文字列の履歴に依存します; しかし理論的には、これはバイトの列ではなく文字の列です。 これに関するチュートリアルについては perlunitut を参照してください。

Let us now discuss Unicode character classes, most usually called "character properties". These are represented by the \p{name} escape sequence. The negation of this is \P{name}. For example, to match lower and uppercase characters,

ほとんどの場合「文字特性」と呼ばれる、Unicode 文字クラスについて述べましょう。 これらは \p{name} エスケープシーケンスで表されます。 この否定は \P{name} です。 たとえば小文字や大文字の文字にマッチングさせるには、

    $x = "BOB";
    $x =~ /^\p{IsUpper}/;   # matches, uppercase char class
    $x =~ /^\P{IsUpper}/;   # doesn't match, char class sans uppercase
    $x =~ /^\p{IsLower}/;   # doesn't match, lowercase char class
    $x =~ /^\P{IsLower}/;   # matches, char class sans lowercase
    $x = "BOB";
    $x =~ /^\p{IsUpper}/;   # マッチングする; 大文字の文字クラス
    $x =~ /^\P{IsUpper}/;   # マッチングしない; 文字クラスは大文字以外
    $x =~ /^\p{IsLower}/;   # マッチングしない; 小文字の文字クラス
    $x =~ /^\P{IsLower}/;   # マッチングする; 文字クラスは小文字以外

(The "Is" is optional.)

("Is" はオプションです。)

There are many, many Unicode character properties. For the full list see perluniprops. Most of them have synonyms with shorter names, also listed there. Some synonyms are a single character. For these, you can drop the braces. For instance, \pM is the same thing as \p{Mark}, meaning things like accent marks.

Unicode 文字特性はとてもとてもたくさんあります。 完全な一覧については perluniprops を参照してください。 これらのほとんどはより短い名前の同義語で、これらも一覧されています。 一文字の同義語もあります。 これらについては、中かっこを省略できます。 例えば、\pM\p{Mark} と同じことで、アクセント記号のようなものを 意味します。

The Unicode \p{Script} and \p{Script_Extensions} properties are used to categorize every Unicode character into the language script it is written in. For example, English, French, and a bunch of other European languages are written in the Latin script. But there is also the Greek script, the Thai script, the Katakana script, etc. (Script is an older, less advanced, form of Script_Extensions, retained only for backwards compatibility.) You can test whether a character is in a particular script with, for example \p{Latin}, \p{Greek}, or \p{Katakana}. To test if it isn't in the Balinese script, you would use \P{Balinese}. (These all use Script_Extensions under the hood, as that gives better results.)

Unicode の \p{Script}\p{Script_Extensions} 特性は、全ての Unicode 文字を、それが書かれる言語用字に分類します。 しかし、ギリシャ用字、タイ用字、カタカナ用字などもあります。 (ScriptScript_Extensions の古い版で、後方互換性のためだけに 残されています。) 例えば、英語、フランス語、および多くのその他のヨーロッパ言語は ラテン用字で書かれます。 ある文字が特定の用字に含まれるかを、例えば \p{Latin}, \p{Greek}, \p{Katakana} のようにしてテスト出来ます。 バリ用字に含まれていないことをテストするには、 \P{Balinese} として使います。 (これら全ては水面下で Script_Extensions を使います; よりよい結果が 得られるからです。)

What we have described so far is the single form of the \p{...} character classes. There is also a compound form which you may run into. These look like \p{name=value} or \p{name:value} (the equals sign and colon can be used interchangeably). These are more general than the single form, and in fact most of the single forms are just Perl-defined shortcuts for common compound forms. For example, the script examples in the previous paragraph could be written equivalently as \p{Script_Extensions=Latin}, \p{Script_Extensions:Greek}, \p{script_extensions=katakana}, and \P{script_extensions=balinese} (case is irrelevant between the {} braces). You may never have to use the compound forms, but sometimes it is necessary, and their use can make your code easier to understand.

今のところ記述してきたものは \p{...} 文字クラスの単一形式です。 あなたが出会うであろう複合形式もあります。 これらは \p{name=value}\p{name:value} のような形です (等号とコロンは交換可能です)。 これらは単一形式よりより一般的で、実際ほとんどの単一形式は単に 共通複合形式の Perl 定義のショートカットです。 例えば、以前の段落でのスクリプトの例は \p{Script_Extensions=Latin}, \p{Script_Extensions:Greek}, \p{script_extensions=katakana}, and \P{script_extensions=balinese} と 等価に書けます (大文字小文字は {} の中では無意味です)。 複合形式を使う必要は決してありませんが、ときどき必要になり、これを使うことで コードが理解しやすくなります。

\X is an abbreviation for a character class that comprises a Unicode extended grapheme cluster. This represents a "logical character": what appears to be a single character, but may be represented internally by more than one. As an example, using the Unicode full names, e.g., "A + COMBINING RING" is a grapheme cluster with base character "A" and combining character "COMBINING RING, which translates in Danish to "A" with the circle atop it, as in the word Ångstrom.

\X は、Unicode の 拡張書記素クラスタ (extended grapheme cluster) を 構成する文字クラスの並びの略記です。 これは「論理文字」を表現します: 一つの文字のように見えるけれども、内部では 複数で表現されるものです。 例えば、"A + COMBINING RING" のような Unicode の完全な名前を使うと、 基底文字 "A" と結合文字 COMBINING RING による書記素クラスタで、 これはデンマーク語では "A" の上に丸がついたものに変換され、オングストローム (Ångstrom)という単語で使われます。

For the full and latest information about Unicode see the latest Unicode standard, or the Unicode Consortium's website https://www.unicode.org

Unicode に関するすべての情報や最新の情報を得るには、Unicode standard の 最新のものを見るか、Unicode コンソーシアムの web サイト https://www.unicode.org/ を参照してください。

As if all those classes weren't enough, Perl also defines POSIX-style character classes. These have the form [:name:], with name the name of the POSIX class. The POSIX classes are alpha, alnum, ascii, cntrl, digit, graph, lower, print, punct, space, upper, and xdigit, and two extensions, word (a Perl extension to match \w), and blank (a GNU extension). The /a modifier restricts these to matching just in the ASCII range; otherwise they can match the same as their corresponding Perl Unicode classes: [:upper:] is the same as \p{IsUpper}, etc. (There are some exceptions and gotchas with this; see perlrecharclass for a full discussion.) The [:digit:], [:word:], and [:space:] correspond to the familiar \d, \w, and \s character classes. To negate a POSIX class, put a '^' in front of the name, so that, e.g., [:^digit:] corresponds to \D and, under Unicode, \P{IsDigit}. The Unicode and POSIX character classes can be used just like \d, with the exception that POSIX character classes can only be used inside of a character class:

これらのクラスでは不足と言うかのように、Perl は POSIX 形式の文字クラスも 定義します。 これらは [:name:] の形式で、name は POSIX クラス名です。 POSIX クラスは alpha, alnum, ascii, cntrl, digit, graph, lower, print, punct, space, upper, xdigit および二つの拡張 word (\w にマッチングする Perl 拡張), blank (GNU 拡張) です。 /a 修飾子はこれらを ASCII の範囲だけでマッチングするように制限します; さもなければ対応する Perl Unicode クラスと同じようにマッチングします: [:upper:]\p{IsUpper} と同じ、などです。 (ここにはいくつかの例外とコツがあります; 完全な議論については perlrecharclass を参照してください。) [:digit:], [:word:], [:space:] は親しんでいる \d, \w, \s 文字クラスに対応します。 POSIX クラスを否定するためには名前の前に '^' を置きます; 従って、例えば [:^digit:]\D に対応し、Unicode では \P{IsDigit} に対応します。 Unicode と POSIX の文字クラスはちょうど \d のように使えますが、 POSIX 文字クラスは文字クラスの中でのみ使えます:

    /\s+[abc[:digit:]xyz]\s*/;  # match a,b,c,x,y,z, or a digit
    /^=item\s[[:digit:]]/;      # match '=item',
                                # followed by a space and a digit
    /\s+[abc\p{IsDigit}xyz]\s+/;  # match a,b,c,x,y,z, or a digit
    /^=item\s\p{IsDigit}/;        # match '=item',
                                  # followed by a space and a digit

Whew! That is all the rest of the characters and character classes.

ふう! これが文字と文字クラスで残っていたこと全てです。

正規表現のコンパイルと保管

In Part 1 we mentioned that Perl compiles a regexp into a compact sequence of opcodes. Thus, a compiled regexp is a data structure that can be stored once and used again and again. The regexp quote qr// does exactly that: qr/string/ compiles the string as a regexp and transforms the result into a form that can be assigned to a variable:

パート 1 では、Perl は正規表現をコンパクトなオペコードの並びにコンパイルすると 述べました。 従って、コンパイルされた正規表現は一度だけ格納されて繰り返し使うことのできる データ構造です。 qr// で表される正規表現クォートは次のようなものです: qr/string/string を正規表現としてコンパイルして結果を変数に 代入することのできる形式へと変換します:

    $reg = qr/foo+bar?/;  # reg contains a compiled regexp
    $reg = qr/foo+bar?/;  # reg はコンパイル済み正規表現を保持する

Then $reg can be used as a regexp:

$reg は正規表現として使うことができます:

    $x = "fooooba";
    $x =~ $reg;     # matches, just like /foo+bar?/
    $x =~ /$reg/;   # same thing, alternate form
    $x = "fooooba";
    $x =~ $reg;     # マッチングする; /foo+bar?/ と同様
    $x =~ /$reg/;   # 同じことを別の形式で

$reg can also be interpolated into a larger regexp:

$reg はより大きな正規表現の中で展開することもできます:

    $x =~ /(abc)?$reg/;  # still matches
    $x =~ /(abc)?$reg/;  # これもマッチングする

As with the matching operator, the regexp quote can use different delimiters, e.g., qr!!, qr{} or qr~~. Apostrophes as delimiters (qr'') inhibit any interpolation.

マッチング演算子を伴ったときのように正規表現クォートは qr!!, qr{}, qr~~ のような異なるデリミタを使うことができます。 シングルクォートを使ったデリミタ (qr'') は変数展開を抑止します。

Pre-compiled regexps are useful for creating dynamic matches that don't need to be recompiled each time they are encountered. Using pre-compiled regexps, we write a grep_step program which greps for a sequence of patterns, advancing to the next pattern as soon as one has been satisfied.

コンパイル済み正規表現は、現れるたびにコンパイルする必要のない動的な マッチングを生成するのに便利です。 コンパイル済み正規表現を使って、ひとつのパターンを満足したらすぐに次の パターンに進むような、パターンの並びを grep する grep_step を書けます。

    % cat > grep_step
    #!/usr/bin/perl
    # grep_step - match <number> regexps, one after the other
    # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...

    $number = shift;
    $regexp[$_] = shift foreach (0..$number-1);
    @compiled = map qr/$_/, @regexp;
    while ($line = <>) {
        if ($line =~ /$compiled[0]/) {
            print $line;
            shift @compiled;
            last unless @compiled;
        }
    }
    ^D

    % grep_step 3 shift print last grep_step
    $number = shift;
            print $line;
            last unless @compiled;

Storing pre-compiled regexps in an array @compiled allows us to simply loop through the regexps without any recompilation, thus gaining flexibility without sacrificing speed.

コンパイル済み正規表現を配列 @compiled に格納することで、 再コンパイルすることなく正規表現を使うことができ、これにより 速度を犠牲にすることなく柔軟性を手に入れることができました。

実行時に正規表現を構成する

Backtracking is more efficient than repeated tries with different regular expressions. If there are several regular expressions and a match with any of them is acceptable, then it is possible to combine them into a set of alternatives. If the individual expressions are input data, this can be done by programming a join operation. We'll exploit this idea in an improved version of the simple_grep program: a program that matches multiple patterns:

バックトラッキングは、異なる正規表現を繰り返し試すよりも効果的です。 もしいくつかの正規表現があって、そのどれとマッチングしてもいい場合、 それらを選択肢の集合に結合できます。 もしこの正規表現が入力データなら、これは結合操作をプログラミングすることで 行えます。 このアイデアを simple_grep プログラムの拡張版 (複数のパターンにマッチングするプログラム)で利用することにします:

    % cat > multi_grep
    #!/usr/bin/perl
    # multi_grep - match any of <number> regexps
    # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...

    $number = shift;
    $regexp[$_] = shift foreach (0..$number-1);
    $pattern = join '|', @regexp;

    while ($line = <>) {
        print $line if $line =~ /$pattern/;
    }
    ^D

    % multi_grep 2 shift for multi_grep
    $number = shift;
    $regexp[$_] = shift foreach (0..$number-1);

Sometimes it is advantageous to construct a pattern from the input that is to be analyzed and use the permissible values on the left hand side of the matching operations. As an example for this somewhat paradoxical situation, let's assume that our input contains a command verb which should match one out of a set of available command verbs, with the additional twist that commands may be abbreviated as long as the given string is unique. The program below demonstrates the basic algorithm.

入力を検査して、マッチング操作の左側に許される値として使うために パターンを構築することには好都合な場合もあります。 このいくらか奇妙な状況の例として、入力は与えられたコマンド動詞の集合の どれか一つにマッチングするもので、かつ、与えられた文字列がユニークで ある限りコマンド名を省略できる、と仮定します。 以下のプログラムは基本的なアルゴリズムを例示します。

    % cat > keymatch
    #!/usr/bin/perl
    $kwds = 'copy compare list print';
    while( $cmd = <> ){
        $cmd =~ s/^\s+|\s+$//g;  # trim leading and trailing spaces
        if( ( @matches = $kwds =~ /\b$cmd\w*/g ) == 1 ){
            print "command: '@matches'\n";
        } elsif( @matches == 0 ){
            print "no such command: '$cmd'\n";
        } else {
            print "not unique: '$cmd' (could be one of: @matches)\n";
        }
    }
    ^D

    % keymatch
    li
    command: 'list'
    co
    not unique: 'co' (could be one of: copy compare)
    printer
    no such command: 'printer'

Rather than trying to match the input against the keywords, we match the combined set of keywords against the input. The pattern matching operation $kwds =~ /\b($cmd\w*)/g does several things at the same time. It makes sure that the given command begins where a keyword begins (\b). It tolerates abbreviations due to the added \w*. It tells us the number of matches (scalar @matches) and all the keywords that were actually matched. You could hardly ask for more.

入力をキーワードとマッチングしようとするのではなく、キーワードの 集合を結合したものを入力とマッチングします。 パターンマッチング操作 $kwds =~ /\b($cmd\w*)/g は 同時に複数のことを行います。 これは与えられたコマンドがキーワードの開始位置で始まることを確認します (\b)。 これは \w* を追加することによって短縮を許容します。 これはマッチングした数 (scalar @matches) と、実際にマッチングした キーワードを知らせます。 これ以上聞きたいこともないでしょう。

正規表現にコメントや修飾子を埋め込む

Starting with this section, we will be discussing Perl's set of extended patterns. These are extensions to the traditional regular expression syntax that provide powerful new tools for pattern matching. We have already seen extensions in the form of the minimal matching constructs ??, *?, +?, {n,m}?, {n,}?, and {,n}?. Most of the extensions below have the form (?char...), where the char is a character that determines the type of extension.

このセクションのはじめで、Perl の 拡張パターン(extended patterns)の 集合について述べると言いました。 以下に述べるのは、伝統的な正規表現構文を拡張して、パターンマッチングに おいて新しい強力なツールを提供するものです。 すでに、??, *?, +?, {n,m}?, {n,}?, {,n}? といった 最小マッチングの拡張について述べました。 後述する拡張のほとんどは (?char...) という形式で、char は 拡張の型を指定する文字です。

The first extension is an embedded comment (?#text). This embeds a comment into the regular expression without affecting its meaning. The comment should not have any closing parentheses in the text. An example is

最初の拡張はコメント (?#text) です。 これは正規表現に、その意味を変更することなくコメントを埋め込みます。 コメントはテキストの中で閉じカッコ以外の任意のものを持てます。 例を挙げましょう

    /(?# Match an integer:)[+-]?\d+/;

This style of commenting has been largely superseded by the raw, freeform commenting that is allowed with the /x modifier.

このスタイルのコメントは、/x 修飾子を使ったときの自由形式の コメントにとって代わられています。

Most modifiers, such as /i, /m, /s and /x (or any combination thereof) can also be embedded in a regexp using (?i), (?m), (?s), and (?x). For instance,

/i, /m, /s, /x のようなほとんどの修飾子(あるいはその 組み合わせ)は (?i), (?m), (?s), (?x) を使って正規表現に 埋め込むこともできます。 たとえば:

    /(?i)yes/;  # match 'yes' case insensitively
    /yes/i;     # same thing
    /(?x)(          # freeform version of an integer regexp
             [+-]?  # match an optional sign
             \d+    # match a sequence of digits
         )
    /x;
    /(?i)yes/;  # 大小文字の違いを無視して 'yes' にマッチング
    /yes/i;     # 同じこと
    /(?x)(          # 自由形式の整数にマッチングする正規表現
             [+-]?  # 省略可能な符号
             \d+    # 数字の並びにマッチング
         )
    /x;

Embedded modifiers can have two important advantages over the usual modifiers. Embedded modifiers allow a custom set of modifiers for each regexp pattern. This is great for matching an array of regexps that must have different modifiers:

埋め込み修飾子は通常の修飾子に比べて二つの利点があります。 埋め込み修飾子は正規表現のパターンの それぞれに 別々の修飾子を 与えることができます。 これは異なる修飾子を持った正規表現の配列にマッチングさせるのに有利です:

    $pattern[0] = '(?i)doctor';
    $pattern[1] = 'Johnson';
    ...
    while (<>) {
        foreach $patt (@pattern) {
            print if /$patt/;
        }
    }

The second advantage is that embedded modifiers (except /p, which modifies the entire regexp) only affect the regexp inside the group the embedded modifier is contained in. So grouping can be used to localize the modifier's effects:

二番目の利点は、埋め込み修飾子(正規表現全体を修正する /p を除きます) はそれが埋め込まれたグループの中にある正規表現にだけ影響するということです。 このため、グループ化を修飾子の影響を局所化するために使うことができます:

    /Answer: ((?i)yes)/;  # matches 'Answer: yes', 'Answer: YES', etc.
    /Answer: ((?i)yes)/;  # 'Answer: yes', 'Answer: YES' などにマッチング

Embedded modifiers can also turn off any modifiers already present by using, e.g., (?-i). Modifiers can also be combined into a single expression, e.g., (?s-i) turns on single line mode and turns off case insensitivity.

埋め込み修飾子は (?-i) のようにして任意の修飾子を無効にすることも できます。 修飾子は一つの式にまとめることもでき、たとえば (?s-i) は 単一行モードを有効にして大小文字の違いを無視ししないようにします。

Embedded modifiers may also be added to a non-capturing grouping. (?i-m:regexp) is a non-capturing grouping that matches regexp case insensitively and turns off multi-line mode.

埋め込みの修飾子は非捕捉グループ化にも追加できます。 (?i-m:regexp)regexp に大小文字の違いを無視してマッチングし 複数行モードをオフにする非捕捉グループ化です。

先読みと戻り読み

This section concerns the lookahead and lookbehind assertions. First, a little background.

本セクションでは先読み(lookahead)と戻り読み(後読み: lookbehind)の 表明について述べます。 まずはじめにちょっとした背景から。

In Perl regular expressions, most regexp elements "eat up" a certain amount of string when they match. For instance, the regexp element [abc] eats up one character of the string when it matches, in the sense that Perl moves to the next character position in the string after the match. There are some elements, however, that don't eat up characters (advance the character position) if they match. The examples we have seen so far are the anchors. The anchor '^' matches the beginning of the line, but doesn't eat any characters. Similarly, the word boundary anchor \b matches wherever a character matching \w is next to a character that doesn't, but it doesn't eat up any characters itself. Anchors are examples of zero-width assertions: zero-width, because they consume no characters, and assertions, because they test some property of the string. In the context of our walk in the woods analogy to regexp matching, most regexp elements move us along a trail, but anchors have us stop a moment and check our surroundings. If the local environment checks out, we can proceed forward. But if the local environment doesn't satisfy us, we must backtrack.

Perlの正規表現では、ほとんどの正規表現要素はそれにマッチングしたときに文字列の 一部を「食い取り」(eat up)します。 たとえば、[abc] という正規表現要素はそれにマッチングしたときに文字列の 文字一つを食い取ります; そして Perl はマッチングの後で文字列の次の位置の 文字へと移動します。 しかしながら、マッチングしたときに文字を食い取らない(が、文字位置は進める) 要素が存在します。 その例はアンカーとしてすでに登場しています。 '^' というアンカーは行の先頭にマッチングしますが文字を食い取ることはしません。 同様に語境界アンカー \b はたとえば単語を構成する文字で、次が単語を 構成する文字でない場所にマッチングしますが、文字を食い取ることはしません。 アンカーは「ゼロ幅の表明」(zero-width assertions) の実例です: 文字を消費しないのでゼロ幅で、文字列のなんらかの属性をテストするので 表明です。 正規表現のマッチングを森の中での歩行にたとえた文脈で言えば、大部分の 正規表現要素は移動を伴うものであるが、アンカーは足を止めて周囲を 確認するようなものです。 局所的な環境をチェックしたなら、進むことができます。 しかし局所的な環境が私たちを満足するものでなければ、私たちは 後戻りしなければなりません。

Checking the environment entails either looking ahead on the trail, looking behind, or both. '^' looks behind, to see that there are no characters before. '$' looks ahead, to see that there are no characters after. \b looks both ahead and behind, to see if the characters on either side differ in their "word-ness".

環境をチェックすることは道の上で先を見通したり、後ろを振り返ったり することです。 '^' は後ろを振り返って、文字が存在していないかどうかを確認します。 '$' は先を見て、更に文字が続いていないかどうかを確認します。 \b は先や後ろを、そこにある文字がそれぞれに対して異なる 単語属性("word-ness")であるかどうかを確認します。

The lookahead and lookbehind assertions are generalizations of the anchor concept. Lookahead and lookbehind are zero-width assertions that let us specify which characters we want to test for. The lookahead assertion is denoted by (?=regexp) or (starting in 5.32, experimentally in 5.28) (*pla:regexp) or (*positive_lookahead:regexp); and the lookbehind assertion is denoted by (?<=fixed-regexp) or (starting in 5.32, experimentally in 5.28) (*plb:fixed-regexp) or (*positive_lookbehind:fixed-regexp). Some examples are

先読み表明や戻り読み表明はアンカーの考え方を一般化したものです。 先読み表明と戻り読み表明はゼロ幅の表明で、文字が テストしたいものであることを指定します。 先読み表明は (?=regexp)、あるいは (5.32 から、5.28 からは実験的) (*pla:regexp) または (*positive_lookahead:regexp) で表されます; 戻り読み表明は (?<=fixed-regexp) で表されます あるいは (5.32 から、5.28 から実験的) (*plb:fixed-regexp) または (*positive_lookbehind:fixed-regexp)。 いくつか例を挙げましょう:

    $x = "I catch the housecat 'Tom-cat' with catnip";
    $x =~ /cat(*pla:\s)/;   # matches 'cat' in 'housecat'
    @catwords = ($x =~ /(?<=\s)cat\w+/g);  # matches,
                                           # $catwords[0] = 'catch'
                                           # $catwords[1] = 'catnip'
    $x =~ /\bcat\b/;  # matches 'cat' in 'Tom-cat'
    $x =~ /(?<=\s)cat(?=\s)/; # doesn't match; no isolated 'cat' in
                              # middle of $x
    $x = "I catch the housecat 'Tom-cat' with catnip";
    $x =~ /cat(?=\s)/;   # 'housecat'の'cat'にマッチング
    @catwords = ($x =~ /(?<=\s)cat\w+/g);  # マッチングする
                                           # $catwords[0] = 'catch'
                                           # $catwords[1] = 'catnip'
    $x =~ /\bcat\b/;  # 'Tom-cat'の'cat'にマッチング
    $x =~ /(?<=\s)cat(?=\s)/; # マッチングしない; $xの中間に 'cat' はない

Note that the parentheses in these are non-capturing, since these are zero-width assertions. Thus in the second regexp, the substrings captured are those of the whole regexp itself. Lookahead can match arbitrary regexps, but lookbehind prior to 5.30 (?<=fixed-regexp) only works for regexps of fixed width, i.e., a fixed number of characters long. Thus (?<=(ab|bc)) is fine, but (?<=(ab)*) prior to 5.30 is not.

これらの中にあるカッコが、これらがゼロ幅の 表明であるために捕捉を行わないことに注意してください。 したがって、二番目の正規表現では捕捉された部分文字列は 正規表現全体に対応するものになります。 先読み表明には任意の正規表現を使うことができますが、 5.30 より前の戻り読み表明 (?<=fixed-regexp) は固定長の正規表現、 たとえば固定長の文字並びでのみ使うことができます。 このため、(?<=(ab|bc)) は大丈夫ですが、 5.30 より前の (?<=(ab)*) は使えません。

The negated versions of the lookahead and lookbehind assertions are denoted by (?!regexp) and (?<!fixed-regexp) respectively. Or, starting in 5.32 (experimentally in 5.28), (*nla:regexp), (*negative_lookahead:regexp), (*nlb:regexp), or (*negative_lookbehind:regexp). They evaluate true if the regexps do not match:

先読み表明と戻り読み表明の否定形はそれぞれ (?!regexp)(?<!fixed-regexp) で表されます。 あるいは、5.32 から (5.28 から実験的)、(*nla:regexp), (*negative_lookahead:regexp), (*nlb:regexp), (*negative_lookbehind:regexp) です。 これらはその正規表現がマッチングしなかったときに真となります。

    $x = "foobar";
    $x =~ /foo(?!bar)/;  # doesn't match, 'bar' follows 'foo'
    $x =~ /foo(?!baz)/;  # matches, 'baz' doesn't follow 'foo'
    $x =~ /(?<!\s)foo/;  # matches, there is no \s before 'foo'
    $x = "foobar";
    $x =~ /foo(?!bar)/;  # マッチングしない; 'bar' が 'foo' に続いている
    $x =~ /foo(?!baz)/;  # マッチングする; 'baz' は 'foo' に続いていない
    $x =~ /(?<!\s)foo/;  # マッチングする; \s は 'foo' の前にない

Here is an example where a string containing blank-separated words, numbers and single dashes is to be split into its components. Using /\s+/ alone won't work, because spaces are not required between dashes, or a word or a dash. Additional places for a split are established by looking ahead and behind:

これは、空白で区切られた単語、数値、一つのダッシュを含む文字列を、その要素で split するという例です。 単に /\s+/ だけを使っても動作しません; なぜならダッシュの間、単語、 ダッシュには空白が不要だからです。 split のための追加の場所は前方参照と後方参照で構築されます:

    $str = "one two - --6-8";
    @toks = split / \s+              # a run of spaces
                  | (?<=\S) (?=-)    # any non-space followed by '-'
                  | (?<=-)  (?=\S)   # a '-' followed by any non-space
                  /x, $str;          # @toks = qw(one two - - - 6 - 8)

バックトラッキングの抑制のために独立部分式を使う

Independent subexpressions (or atomic subexpressions) are regular expressions, in the context of a larger regular expression, that function independently of the larger regular expression. That is, they consume as much or as little of the string as they wish without regard for the ability of the larger regexp to match. Independent subexpressions are represented by (?>regexp) or (starting in 5.32, experimentally in 5.28) (*atomic:regexp). We can illustrate their behavior by first considering an ordinary regexp:

独立部分式 (independent subexpressions) (またはアトミック部分式 (atomic subexpressions)) はより大きな正規表現の中で 独立した機能を持った正規表現です。 つまり、より大きな正規表現がマッチングすることには関係なく、望む限りの大きな 文字列もしくは望む限りの小さな文字列にマッチングしたものを消費します。 独立部分式は (?>regexp) または (5.32 から、実験的には 5.28 から) (*atomic:regexp) で表されます。 これの振る舞いを通常の正規表現を使って説明しましょう:

    $x = "ab";
    $x =~ /a*ab/;  # matches
    $x = "ab";
    $x =~ /a*ab/;  # マッチングする

This obviously matches, but in the process of matching, the subexpression a* first grabbed the 'a'. Doing so, however, wouldn't allow the whole regexp to match, so after backtracking, a* eventually gave back the 'a' and matched the empty string. Here, what a* matched was dependent on what the rest of the regexp matched.

これは明らかにマッチングしますが、しかし、マッチングのプロセスにおいて 部分式 a* は最初に 'a' をつかみとります。 それを行うことによって、正規表現全体がマッチングすることを許さず、そのために バックトラッキングが起きて a*'a' を戻して空文字列にマッチングします。 ここで、a* は正規表現の残りの部分のマッチングに依存してマッチングしました。

Contrast that with an independent subexpression:

独立部分式を使うと対照的に:

    $x =~ /(?>a*)ab/;  # doesn't match!
    $x =~ /(?>a*)ab/;  # マッチングしない!

The independent subexpression (?>a*) doesn't care about the rest of the regexp, so it sees an 'a' and grabs it. Then the rest of the regexp ab cannot match. Because (?>a*) is independent, there is no backtracking and the independent subexpression does not give up its 'a'. Thus the match of the regexp as a whole fails. A similar behavior occurs with completely independent regexps:

この独立部分式 (?>a*) は正規表現の残りの部分を考慮しません; そのため、'a' を見つけたらそれをつかみとります。 そして残りの正規表現 ab はマッチングできません。 (?>a*) は独立しているので、バックトラッキングは行わず、独立部分式は 'a' を戻すこともありません。 結果として正規表現全体のマッチングは失敗します。 同様の動作が、完全に独立した正規表現においても発生します:

    $x = "ab";
    $x =~ /a*/g;   # matches, eats an 'a'
    $x =~ /\Gab/g; # doesn't match, no 'a' available
    $x = "ab";
    $x =~ /a*/g;   # マッチングする; 'a' を食い取る
    $x =~ /\Gab/g; # マッチングしない; 'a' がない

Here /g and \G create a "tag team" handoff of the string from one regexp to the other. Regexps with an independent subexpression are much like this, with a handoff of the string to the independent subexpression, and a handoff of the string back to the enclosing regexp.

ここで、/g\G は「タッグチーム」を結成していて、一つの 正規表現から別の正規表現へと文字列を手渡ししています。 独立部分式を持った正規表現はこれと同じようにマッチングし、独立部分式に文字列を 手渡しして、それにマッチングした文字列を戻します。

The ability of an independent subexpression to prevent backtracking can be quite useful. Suppose we want to match a non-empty string enclosed in parentheses up to two levels deep. Then the following regexp matches:

バックトラッキングを阻止するという独立部分式の能力はとても便利です。 2 レベルの深さを持つカッコに囲まれた空でない文字列にマッチングさせることを 考えてみましょう。 それは以下のような正規表現になります:

    $x = "abc(de(fg)h";  # unbalanced parentheses
    $x =~ /\( ( [ ^ () ]+ | \( [ ^ () ]* \) )+ \)/xx;
    $x = "abc(de(fg)h";  # 対応の取れていないかっこ
    $x =~ /\( ( [ ^ () ]+ | \( [ ^ () ]* \) )+ \)/xx;

The regexp matches an open parenthesis, one or more copies of an alternation, and a close parenthesis. The alternation is two-way, with the first alternative [^()]+ matching a substring with no parentheses and the second alternative \([^()]*\) matching a substring delimited by parentheses. The problem with this regexp is that it is pathological: it has nested indeterminate quantifiers of the form (a+|b)+. We discussed in Part 1 how nested quantifiers like this could take an exponentially long time to execute if there is no match possible. To prevent the exponential blowup, we need to prevent useless backtracking at some point. This can be done by enclosing the inner quantifier as an independent subexpression:

この正規表現は開きかっこ、選択肢にある一つか二つのコピー、そして 閉じかっこにマッチングします。 この選択肢は二分岐で、最初の選択肢は括弧のない部分文字列にマッチングする [^()]+ で、二番目の選択肢はかっこによって区切られた部分文字列に マッチングする \([^()]*\) です。 この正規表現の問題点は病理学的なものです: (a+|b)+ のように非決定的な 量指定子がネストしています。 パート 1 において、ネストした量指定子はマッチングに失敗するときには実行に 指数的な時間を要することについて言及しました。 これを防ぐために、不要なバックトラッキングを抑制することが必要となります。 これは内側の量指定子を独立部分式としてやることで行うことができます:

    $x =~ /\( ( (?> [ ^ () ]+ ) | \([ ^ () ]* \) )+ \)/xx;

Here, (?>[^()]+) breaks the degeneracy of string partitioning by gobbling up as much of the string as possible and keeping it. Then match failures fail much more quickly.

ここで、(?>[^()]+) は可能な限りマッチングしたものをつかみとって 保持することによって文字列の分割の退行を邪魔しています。 それからマッチングは即座に失敗することになります。

条件式

A conditional expression is a form of if-then-else statement that allows one to choose which patterns are to be matched, based on some condition. There are two types of conditional expression: (?(condition)yes-regexp) and (?(condition)yes-regexp|no-regexp). (?(condition)yes-regexp) is like an 'if () {}' statement in Perl. If the condition is true, the yes-regexp will be matched. If the condition is false, the yes-regexp will be skipped and Perl will move onto the next regexp element. The second form is like an 'if () {} else {}' statement in Perl. If the condition is true, the yes-regexp will be matched, otherwise the no-regexp will be matched.

条件式 (conditional expression) は if-the-else の形式の文で、何らかの 条件に基づいてどちらのパターンをマッチングさせるかを選択できます。 条件式には二つのタイプがあります: (?(condition)yes-regexp)(?(condition)yes-regexp|no-regexp) です。 (?(condition)yes-regexp) は Perl の 'if () {}' 文のようなものです。 もし condition が真であれば、yes-regexp がマッチングの対象となります。 condition が偽であった場合、yes-regexp はスキップされて、 Perl は次の正規表現要素へと進みます。 二番目の形式は Perl の 'if () {} else {}' 文のようなものです。 conditon が真であれば yes-regexp がマッチングの対象となり、偽であれば no-regexp がマッチングの対象となります。

The condition can have several forms. The first form is simply an integer in parentheses (integer). It is true if the corresponding backreference \integer matched earlier in the regexp. The same thing can be done with a name associated with a capture group, written as (<name>) or ('name'). The second form is a bare zero-width assertion (?...), either a lookahead, a lookbehind, or a code assertion (discussed in the next section). The third set of forms provides tests that return true if the expression is executed within a recursion ((R)) or is being called from some capturing group, referenced either by number ((R1), (R2),...) or by name ((R&name)).

condition はいくつかのの形式を取ることができます。 最初の形式は単純な整数をカッコでくくったもの (integer) です。 これは対応する後方参照 \integer が先行する正規表現の部分の中で マッチングしていれば真となります。 同じことは、捕捉グループに結び付けられた名前を使って、 (<name>)('name') のように書くことでもできます。 二番目の形式はゼロ幅の表明 (?...) で、先読み、戻り読み、もしくは コード表明 (code assertion 次のセクションで説明します)のいずれかです。 3番目の形式は、もし式が再帰 ((R)) の中で実行されるか、 数値 ((R1), (R2),...) か名前 ((R&name)) で参照される捕捉グループから 呼び出されていると真を返すというテストを提供します。

The integer or name form of the condition allows us to choose, with more flexibility, what to match based on what matched earlier in the regexp. This searches for words of the form "$x$x" or "$x$y$y$x":

整数または名前形式の condition はより一層の融通性を伴って選択することを 可能にします; マッチングするかどうかは正規表現の先行する部分が マッチングするかどうかに依存します。 以下の例は "$x$x""$x$y$y$x" という形式の単語を検索します。

    % simple_grep '^(\w+)(\w+)?(?(2)\g2\g1|\g1)$' /usr/dict/words
    beriberi
    coco
    couscous
    deed
    ...
    toot
    toto
    tutu

The lookbehind condition allows, along with backreferences, an earlier part of the match to influence a later part of the match. For instance,

戻り読みの condition は後方参照といっしょで、マッチングの先行する部分が マッチングの後ろの部分に影響を及ぼします。 たとえば:

    /[ATGC]+(?(?<=AA)G|C)$/;

matches a DNA sequence such that it either ends in AAG, or some other base pair combination and 'C'. Note that the form is (?(?<=AA)G|C) and not (?((?<=AA))G|C); for the lookahead, lookbehind or code assertions, the parentheses around the conditional are not needed.

これは AAG で終わるかその他の 'C' とのコンビネーションのペアと なっている DNA シーケンスにマッチングします。 この形式は (?(?<=AA)G|C) であって、 (?((?<=AA))G|C) でないことに注意してください; 先読み、戻り読み、コードの表明に対しては条件部分を囲むカッコは 必要ありません。

名前付きパターンを定義する

Some regular expressions use identical subpatterns in several places. Starting with Perl 5.10, it is possible to define named subpatterns in a section of the pattern so that they can be called up by name anywhere in the pattern. This syntactic pattern for this definition group is (?(DEFINE)(?<name>pattern)...). An insertion of a named pattern is written as (?&name).

同じ部分パターンを複数の箇所で使う正規表現もあります。 Perl 5.10 から、パターンのどこでも名前で呼び出せるようにするために、 パターンの一部で名前付き部分パターンを定義できるようになっています。 この定義グループのためのパターン文法は (?(DEFINE)(?<name>pattern)...) です。 名前付きパターンの挿入は (?&name) のように書きます。

The example below illustrates this feature using the pattern for floating point numbers that was presented earlier on. The three subpatterns that are used more than once are the optional sign, the digit sequence for an integer and the decimal fraction. The DEFINE group at the end of the pattern contains their definition. Notice that the decimal fraction pattern is the first place where we can reuse the integer pattern.

以下の例では以前に説明した浮動小数点数のためのパターンを使った この機能を示しています。 複数回使われる 3 つの副パターンは、省略可能の符号、整数のための 数字並び、小数点です。 パターンの末尾の DEFINE グループはこれらの定義を含んでいます。 小数点のパターンは整数のパターンを再利用できる最初の位置であることに 注意してください。

   /^ (?&osg)\ * ( (?&int)(?&dec)? | (?&dec) )
      (?: [eE](?&osg)(?&int) )?
    $
    (?(DEFINE)
      (?<osg>[-+]?)         # optional sign
      (?<int>\d++)          # integer
      (?<dec>\.(?&int))     # decimal fraction
    )/x

再帰的パターン

This feature (introduced in Perl 5.10) significantly extends the power of Perl's pattern matching. By referring to some other capture group anywhere in the pattern with the construct (?group-ref), the pattern within the referenced group is used as an independent subpattern in place of the group reference itself. Because the group reference may be contained within the group it refers to, it is now possible to apply pattern matching to tasks that hitherto required a recursive parser.

(Perl 5.10 から導入された)この機能は、Perl のパターンマッチングの力を 大きく拡張します。 パターン中の任意の位置の捕捉グループを (?group-ref) 定数で 参照することで、 参照されたグループ内の パターン はグループ参照自身の代わりに 独立した副パターンとして使われます。 グループ参照は参照しているグループの 内側 に含まれる場合もあるので、 今までは再帰パーサが必要であった処理に対してパターンマッチングを 適用できるようになります。

To illustrate this feature, we'll design a pattern that matches if a string contains a palindrome. (This is a word or a sentence that, while ignoring spaces, interpunctuation and case, reads the same backwards as forwards. We begin by observing that the empty string or a string containing just one word character is a palindrome. Otherwise it must have a word character up front and the same at its end, with another palindrome in between.

この機能を説明するために、文字列が回文である場合にマッチングするパターンを 設計します。 (回文とは、空白、句読点、大文字小文字を無視したとき、 先頭から読んでも末尾から読んでも同じになる単語や文のことです。) まず、空文字列あるいは一つの単語文字からなる文字列を回文として 観測することから始めます。 さもなければ、回文とは先頭と末尾に同じ単語文字があって、その間に 回文があるものです。

 /(?: (\w) (?...Here be a palindrome...) \g{ -1 } | \w? )/x
 /(?: (\w) (?...ここは回文...) \g{ -1 } | \w? )/x

Adding \W* at either end to eliminate what is to be ignored, we already have the full pattern:

無視するべきものを削除するためにどちらかの側に \W* を追加して、すでに 完全なパターンを得ています:

    my $pp = qr/^(\W* (?: (\w) (?1) \g{-1} | \w? ) \W*)$/ix;
    for $s ( "saippuakauppias", "A man, a plan, a canal: Panama!" ){
        print "'$s' is a palindrome\n" if $s =~ /$pp/;
    }

In (?...) both absolute and relative backreferences may be used. The entire pattern can be reinserted with (?R) or (?0). If you prefer to name your groups, you can use (?&name) to recurse into that group.

(?...) の中では絶対と相対の両方の後方参照が使えます。 パターン全体は (?R) または (?0) で再挿入できます。 グループに名前を付けたいなら、そのグループを再帰させるために (?&name) が 使えます。

ちょっとした魔法: 正規表現の中で Perl のコードを実行する

Normally, regexps are a part of Perl expressions. Code evaluation expressions turn that around by allowing arbitrary Perl code to be a part of a regexp. A code evaluation expression is denoted (?{code}), with code a string of Perl statements.

通常、正規表現は Perl の式の一部です。 コード評価 (code evaluation) 式は任意の Perl のコードを正規表現の 一部として使うことができるようにします。 コード評価式は (?{code}) で表され、code は Perl の文である 文字列です。

Code expressions are zero-width assertions, and the value they return depends on their environment. There are two possibilities: either the code expression is used as a conditional in a conditional expression (?(condition)...), or it is not. If the code expression is a conditional, the code is evaluated and the result (i.e., the result of the last statement) is used to determine truth or falsehood. If the code expression is not used as a conditional, the assertion always evaluates true and the result is put into the special variable $^R. The variable $^R can then be used in code expressions later in the regexp. Here are some silly examples:

コード式はゼロ幅の表明で、その値は環境に依存したものです。 そこには二つの可能性があります: コード式が条件式の中で (?(condition)...) のように使われるかそうでないかです。 もしコード式が条件式に使われていれば、そのコードは評価された後その結果 (最後の文の結果)が真か偽かを決定するのに使われます。 コード式が条件式として使われていなければ、その表明は常に真であり その結果は特殊変数 $^R に格納されます。 変数 $^R は正規表現の後の部分のコード式で使うことができます。 以下に単純な例を挙げます:

    $x = "abcdef";
    $x =~ /abc(?{print "Hi Mom!";})def/; # matches,
                                         # prints 'Hi Mom!'
    $x =~ /aaa(?{print "Hi Mom!";})def/; # doesn't match,
                                         # no 'Hi Mom!'
    $x = "abcdef";
    $x =~ /abc(?{print "Hi Mom!";})def/; # マッチングする
                                         # 'Hi Mom!' を主力
    $x =~ /aaa(?{print "Hi Mom!";})def/; # マッチングしない
                                         # 'Hi Mom!'は出力されない

Pay careful attention to the next example:

次の例に注目してください:

    $x =~ /abc(?{print "Hi Mom!";})ddd/; # doesn't match,
                                         # no 'Hi Mom!'
                                         # but why not?
    $x =~ /abc(?{print "Hi Mom!";})ddd/; # マッチングしない;
                                         # 'Hi Mom!' は出力されない
                                         # でもなぜ?

At first glance, you'd think that it shouldn't print, because obviously the ddd isn't going to match the target string. But look at this example:

ぱっと見て、出力されないとは思わなかったでしょう; なぜなら ddd は 明らかにターゲット文字列にマッチングするものではないからです。 しかし次の例を見ると:

    $x =~ /abc(?{print "Hi Mom!";})[dD]dd/; # doesn't match,
                                            # but _does_ print
    $x =~ /abc(?{print "Hi Mom!";})[dD]dd/; # マッチングしない;
                                            # しかし出力「される」

Hmm. What happened here? If you've been following along, you know that the above pattern should be effectively (almost) the same as the last one; enclosing the 'd' in a character class isn't going to change what it matches. So why does the first not print while the second one does?

ふーむ。 何が起きたのでしょう? 先のパターンが効果としては最後のものと (ほとんど) 同じであることをあなたは 知っています; 文字クラスの中に閉じ込められた 'd' はマッチングを 変えるものではありません。 では、なぜ最初のパターンは出力されないのに二番目のものは 出力されたのでしょう?

The answer lies in the optimizations the regexp engine makes. In the first case, all the engine sees are plain old characters (aside from the ?{} construct). It's smart enough to realize that the string 'ddd' doesn't occur in our target string before actually running the pattern through. But in the second case, we've tricked it into thinking that our pattern is more complicated. It takes a look, sees our character class, and decides that it will have to actually run the pattern to determine whether or not it matches, and in the process of running it hits the print statement before it discovers that we don't have a match.

その答えは正規表現エンジンが行う最適化にあります。 最初のケースでは、 エンジンが見ているものは普通の古い文字(?{} 構造は別として) です。 パターンを実際に実行するよりも前にターゲット文字列が 'ddd' という 文字列を含んでいないことがわかるくらい賢いのです。 しかし二番目のケースでは、より複雑なパターンであると 思わせるようなトリックを使いました。 文字クラスを見て、エンジンはマッチングするかどうかは実際にパターンを 実行してみなければならないと判断し、その実行の最中にマッチングしないことが わかるよりも前にある print 文にヒットするのです。

To take a closer look at how the engine does optimizations, see the section "Pragmas and debugging" below.

エンジンがどのように最適化を行うかについては後にあるセクション "Pragmas and debugging" を参照してください。

More fun with ?{}:

?{} でもっと楽しいことが起きます:

    $x =~ /(?{print "Hi Mom!";})/;         # matches,
                                           # prints 'Hi Mom!'
    $x =~ /(?{$c = 1;})(?{print "$c";})/;  # matches,
                                           # prints '1'
    $x =~ /(?{$c = 1;})(?{print "$^R";})/; # matches,
                                           # prints '1'
    $x =~ /(?{print "Hi Mom!";})/;         # マッチングする
                                           # 'Hi Mom!' を出力
    $x =~ /(?{$c = 1;})(?{print "$c";})/;  # マッチングする
                                           # '1' を出力
    $x =~ /(?{$c = 1;})(?{print "$^R";})/; # マッチングする
                                           # '1' を出力

The bit of magic mentioned in the section title occurs when the regexp backtracks in the process of searching for a match. If the regexp backtracks over a code expression and if the variables used within are localized using local, the changes in the variables produced by the code expression are undone! Thus, if we wanted to count how many times a character got matched inside a group, we could use, e.g.,

このセクションのタイトルにある「ちょっとした魔法」というのは マッチングのために検索処理をしているときのバックトラックが 起きたときのことを言っています。 もしバックトラックがコード式をまたいで発生して、local によって その中に局所化された変数を使っていた場合、コード式による変数の変更は 巻き戻されます! したがって、グループの中にある文字の数を数えたい場合には

    $x = "aaaa";
    $count = 0;  # initialize 'a' count
    $c = "bob";  # test if $c gets clobbered
    $x =~ /(?{local $c = 0;})         # initialize count
           ( a                        # match 'a'
             (?{local $c = $c + 1;})  # increment count
           )*                         # do this any number of times,
           aa                         # but match 'aa' at the end
           (?{$count = $c;})          # copy local $c var into $count
          /x;
    print "'a' count is $count, \$c variable is '$c'\n";
    $x = "aaaa";
    $count = 0;  # 'a' のカウントを初期化する
    $c = "bob";  # $c が上書きされているかを調べる
    $x =~ /(?{local $c = 0;})         # カウントを初期化
           ( a                        # 'a' にマッチング
             (?{local $c = $c + 1;})  # カウントをインクリメント
           )*                         # これを任意回繰り返すが
           aa                         # 最後に 'aa' にマッチング
           (?{$count = $c;})          # ローカルの $c を $count にコピー
          /x;
    print "'a' count is $count, \$c variable is '$c'\n";

This prints

これは次を出力します:

    'a' count is 2, $c variable is 'bob'

If we replace the (?{local $c = $c + 1;}) with (?{$c = $c + 1;}), the variable changes are not undone during backtracking, and we get

もし (?{local $c = $c + 1;}) (?{$c = $c + 1;}) にすると、 バックトラックによって変数の変更は 巻き戻されず、結果は 以下のようになります

    'a' count is 4, $c variable is 'bob'

Note that only localized variable changes are undone. Other side effects of code expression execution are permanent. Thus

局所化された変数の変更だけが巻き戻されるということに注意してください。 コード式の別の副作用は恒久的です。 したがって

    $x = "aaaa";
    $x =~ /(a(?{print "Yow\n";}))*aa/;

produces

これは以下の結果となります

   Yow
   Yow
   Yow
   Yow

The result $^R is automatically localized, so that it will behave properly in the presence of backtracking.

結果である $^R は自動的に局所化されるので、バックトラックが 行われても適切に振舞います。

This example uses a code expression in a conditional to match a definite article, either 'the' in English or 'der|die|das' in German:

以下の例は、条件にコード式を使って英語の 'the' か ドイツ語の 'der|die|das' にマッチングさせるものです:

    $lang = 'DE';  # use German
    ...
    $text = "das";
    print "matched\n"
        if $text =~ /(?(?{
                          $lang eq 'EN'; # is the language English?
                         })
                       the |             # if so, then match 'the'
                       (der|die|das)     # else, match 'der|die|das'
                     )
                    /xi;
    $lang = 'DE';  # ドイツ語を使う
    ...
    $text = "das";
    print "matched\n"
        if $text =~ /(?(?{
                          $lang eq 'EN'; # 言語は英語か?
                         })
                       the |             # そうなら 'the' にマッチング
                       (der|die|das)     # そうでないなら 'der|die|das' にマッチング
                     )
                    /xi;

Note that the syntax here is (?(?{...})yes-regexp|no-regexp), not (?((?{...}))yes-regexp|no-regexp). In other words, in the case of a code expression, we don't need the extra parentheses around the conditional.

ここでの構文が (?((?{...}))yes-regexp|no-regexp) ではなく (?(?{...})yes-regexp|no-regexp) であることに注意してください。 言い換えれば、コード式の場合には条件を囲む余計なかっこは いらないということです。

If you try to use code expressions where the code text is contained within an interpolated variable, rather than appearing literally in the pattern, Perl may surprise you:

コード式を、パターン中にリテラルに書くのではなく、展開された変数の中に 入れると、Perl はあなたを驚かせるかもしれません:

    $bar = 5;
    $pat = '(?{ 1 })';
    /foo(?{ $bar })bar/; # compiles ok, $bar not interpolated
    /foo(?{ 1 })$bar/;   # compiles ok, $bar interpolated
    /foo${pat}bar/;      # compile error!
    $bar = 5;
    $pat = '(?{ 1 })';
    /foo(?{ $bar })bar/; # コンパイル ok; $bar は展開されない
    /foo(?{ 1 })$bar/;   # コンパイル ok; $bar は展開される
    /foo${pat}bar/;      # コンパイルエラー!
    $pat = qr/(?{ $foo = 1 })/;  # precompile code regexp
    /foo${pat}bar/;      # compiles ok
    $pat = qr/(?{ $foo = 1 })/;  # コード正規表現をプリコンパイル
    /foo${pat}bar/;      # コンパイル ok

If a regexp has a variable that interpolates a code expression, Perl treats the regexp as an error. If the code expression is precompiled into a variable, however, interpolating is ok. The question is, why is this an error?

もし正規表現がコード式に展開される変数を持っているなら、Perl はその正規表現を エラーとします。 しかしながら、コード式が変数にプリコンパイルされていた場合には、 変数展開は ok です。 疑問は、これがなぜエラーになるかです。

The reason is that variable interpolation and code expressions together pose a security risk. The combination is dangerous because many programmers who write search engines often take user input and plug it directly into a regexp:

その理由は、変数展開とコード式を組み合わせることでセキュリティ上の リスクが発生するからです。 この組み合わせは検索エンジンを記述する多くのプログラマがしばしば ユーザーからの入力を取り、それをダイレクトに変数に押し込むから 危険なのです。

    $regexp = <>;       # read user-supplied regexp
    $chomp $regexp;     # get rid of possible newline
    $text =~ /$regexp/; # search $text for the $regexp
    $regexp = <>;       # ユーザーが提供する正規表現を読み込む
    $chomp $regexp;     # 改行があれば取り除く
    $text =~ /$regexp/; # $text から $regexp を探し出す

If the $regexp variable contains a code expression, the user could then execute arbitrary Perl code. For instance, some joker could search for system('rm -rf *'); to erase your files. In this sense, the combination of interpolation and code expressions taints your regexp. So by default, using both interpolation and code expressions in the same regexp is not allowed. If you're not concerned about malicious users, it is possible to bypass this security check by invoking use re 'eval':

もし変数 $regexp がコード式を含んでいたら、ユーザーは任意の Perl コードを実行することが可能となります。 たとえば、一部の不心得者が system('rm -rf *'); を検索したら、 あなたのファイルを消すことになります。 このため、変数展開とコード式の組み合わせは正規表現を 汚染する ものと みなされます。 そのためデフォルトでは、同じ正規表現の中で変数展開とコード式の両方を 使うことを許していないのです。 もし悪意あるユーザーを考慮しないのであれば、use re 'eval'を 実行することによってセキュリティチェックをバイパスすることが可能です:

    use re 'eval';       # throw caution out the door
    $bar = 5;
    $pat = '(?{ 1 })';
    /foo${pat}bar/;      # compiles ok
    use re 'eval';       # 注意を無視する
    $bar = 5;
    $pat = '(?{ 1 })';
    /foo${pat}bar/;      # コンパイル ok

Another form of code expression is the pattern code expression. The pattern code expression is like a regular code expression, except that the result of the code evaluation is treated as a regular expression and matched immediately. A simple example is

もう一つのコード式は パターンコード式(pattern code expression) です。 パターンコード式は通常のコード式に似ていますが、コードの評価結果が 正規表現として扱われ、即座にマッチングに使われる点が異なります。 単純な例を挙げましょう

    $length = 5;
    $char = 'a';
    $x = 'aaaaabb';
    $x =~ /(??{$char x $length})/x; # matches, there are 5 of 'a'
    $length = 5;
    $char = 'a';
    $x = 'aaaaabb';
    $x =~ /(??{$char x $length})/x; # マッチングする; 5個の 'a'がある

This final example contains both ordinary and pattern code expressions. It detects whether a binary string 1101010010001... has a Fibonacci spacing 0,1,1,2,3,5,... of the '1''s:

最後の例はコード式とパターンコード式の両方を含んだものです。 これは 2 進文字列 1101010010001... に、'1' の フィボナッチ空白 0,1,1,2,3,5,... があるかを見つけ出します:

    $x = "1101010010001000001";
    $z0 = ''; $z1 = '0';   # initial conditions
    print "It is a Fibonacci sequence\n"
        if $x =~ /^1         # match an initial '1'
                    (?:
                       ((??{ $z0 })) # match some '0'
                       1             # and then a '1'
                       (?{ $z0 = $z1; $z1 .= $^N; })
                    )+   # repeat as needed
                  $      # that is all there is
                 /x;
    printf "Largest sequence matched was %d\n", length($z1)-length($z0);

Remember that $^N is set to whatever was matched by the last completed capture group. This prints

$^N は最後に完了した捕捉グループでマッチングしたものがセットされることを 忘れないでください。 これは次を出力します:

    It is a Fibonacci sequence
    Largest sequence matched was 5

Ha! Try that with your garden variety regexp package...

ほら! これを、ありふれた正規表現パッケージで試してみてください…

Note that the variables $z0 and $z1 are not substituted when the regexp is compiled, as happens for ordinary variables outside a code expression. Rather, the whole code block is parsed as perl code at the same time as perl is compiling the code containing the literal regexp pattern.

$z0$z1 という変数は正規表現がコンパイルされたときには、 コード式の外側で通常の変数が使われたときのような置換は行われないということに 注意してください。 代わりに、コードブロック全体は、リテラルな正規表現が含まれたコードが コンパイルされるのと同時に perl によって perl コードとしてパースされます。

This regexp without the /x modifier is

この /x 修飾子がない正規表現は

    /^1(?:((??{ $z0 }))1(?{ $z0 = $z1; $z1 .= $^N; }))+$/

which shows that spaces are still possible in the code parts. Nevertheless, when working with code and conditional expressions, the extended form of regexps is almost necessary in creating and debugging regexps.

のようになり、それでもコード部分には空白を入れることが可能です。 それでもなお、コード式と条件式を使ったときには、正規表現の拡張された形式は 正規表現を生成してデバッグする必要があるでしょう。

バックトラッキング制御動詞

Perl 5.10 introduced a number of control verbs intended to provide detailed control over the backtracking process, by directly influencing the regexp engine and by providing monitoring techniques. See "Special Backtracking Control Verbs" in perlre for a detailed description.

Perl 5.10 から、正規表現エンジンに直接影響を与えることと、監視技術を 提供することによって、バックトラッキング処理を詳細に制御するための 制御同士が導入されました。 "Special Backtracking Control Verbs" in perlre を参照してください。

Below is just one example, illustrating the control verb (*FAIL), which may be abbreviated as (*F). If this is inserted in a regexp it will cause it to fail, just as it would at some mismatch between the pattern and the string. Processing of the regexp continues as it would after any "normal" failure, so that, for instance, the next position in the string or another alternative will be tried. As failing to match doesn't preserve capture groups or produce results, it may be necessary to use this in combination with embedded code.

以下は、制御動詞 (*FAIL) ((*F) と省略できます) を例示した 単なる一つの例です。 これが正規表現に挿入されると、パターンと文字列で不一致があったかのように、 失敗を引き起こします。 正規表現の処理は「通常の」失敗の後のように続行され、 例えば、文字列内の次の位置や、他の選択肢が試行されます。 マッチングの失敗は捕捉グループに保存されたり結果を生成したりしないので、 これは組み込みコードと組み合わせて使う必要があるでしょう。

   %count = ();
   "supercalifragilisticexpialidocious" =~
       /([aeiou])(?{ $count{$1}++; })(*FAIL)/i;
   printf "%3d '%s'\n", $count{$_}, $_ for (sort keys %count);

The pattern begins with a class matching a subset of letters. Whenever this matches, a statement like $count{'a'}++; is executed, incrementing the letter's counter. Then (*FAIL) does what it says, and the regexp engine proceeds according to the book: as long as the end of the string hasn't been reached, the position is advanced before looking for another vowel. Thus, match or no match makes no difference, and the regexp engine proceeds until the entire string has been inspected. (It's remarkable that an alternative solution using something like

パターンは文字のサブクラスにマッチングするクラスで始まります。 どこでマッチングしても、$count{'a'}++; のような分が実行され、 その文字のカウンタをインクリメントします。 それから (*FAIL) がその名前の通りのことを行い、正規表現エンジンは 本に従って続行します: 文字列の末尾に到達するまで、次の母音を探す前の 位置まで進みます。 従って、マッチングしたかどうかには違いはなく、正規表現エンジンは文字列全体が 検査されるまで続行します。 (注意することは、以下のような代替手段は

   $count{lc($_)}++ for split('', "supercalifragilisticexpialidocious");
   printf "%3d '%s'\n", $count2{$_}, $_ for ( qw{ a e i o u } );

is considerably slower.)

かなり遅いということです。)

プラグマとデバッグ

Speaking of debugging, there are several pragmas available to control and debug regexps in Perl. We have already encountered one pragma in the previous section, use re 'eval';, that allows variable interpolation and code expressions to coexist in a regexp. The other pragmas are

デバッグに関して、Perlで正規表現を制御したりデバッグするために幾つかの プラグマがあります。 前のセクションですでに use re 'eval'; という正規表現の中で 変数展開とコード式を共存させることを許可するプラグマが登場しています。 他のプラグマには以下のものがあります

    use re 'taint';
    $tainted = <>;
    @parts = ($tainted =~ /(\w+)\s+(\w+)/; # @parts is now tainted
    use re 'taint';
    $tainted = <>;
    @parts = ($tainted =~ /(\w+)\s+(\w+)/; # @parts は汚染されている

The taint pragma causes any substrings from a match with a tainted variable to be tainted as well, if your perl supports tainting (see perlsec). This is not normally the case, as regexps are often used to extract the safe bits from a tainted variable. Use taint when you are not extracting safe bits, but are performing some other processing. Both taint and eval pragmas are lexically scoped, which means they are in effect only until the end of the block enclosing the pragmas.

taint プラグマは、perl が汚染チェックに対応している (perlsec 参照) 場合、汚染された変数に対するマッチングによる部分文字列を 同様に汚染されたものにするというものです。 これは通常の場合では行われず、正規表現はしばしば汚染された変数から 安全な情報を取り出すのに使われています。 安全な情報を取り出すのではないとき taint を使いますが、他の処理を 行います。 プラグマ tainteval は両方ともレキシカルスコープで、その プラグマを囲むブロックの最後までしか影響が及びません。

    use re '/m';  # or any other flags
    $multiline_string =~ /^foo/; # /m is implied

The re '/flags' pragma (introduced in Perl 5.14) turns on the given regular expression flags until the end of the lexical scope. See "'/flags' mode" in re for more detail.

(Perl 5.14 で導入された) re '/flags' プラグマは、レキシカルスコープの 終わりまで、与えられた正規表現フラグを有効にします。 さらなる詳細は "'/flags' mode" in re を参照してください。

    use re 'debug';
    /^(.*)$/s;       # output debugging info
    use re 'debug';
    /^(.*)$/s;       # デバッグ情報を出力する
    use re 'debugcolor';
    /^(.*)$/s;       # output debugging info in living color
    use re 'debugcolor';
    /^(.*)$/s;       # デバッグ情報を色つきで出力する

The global debug and debugcolor pragmas allow one to get detailed debugging info about regexp compilation and execution. debugcolor is the same as debug, except the debugging information is displayed in color on terminals that can display termcap color sequences. Here is example output:

debug プラグマと debugcolor プラグマは正規表現のコンパイルと 実行に関する詳細なデバッグ情報を提供します。 debugcolordebug と同じですが、デバッグ情報を色付きで (termcap のカラーシーケンスを出力することのできる)ターミナルに出力します。 以下は出力の例です:

    % perl -e 'use re "debug"; "abc" =~ /a*b+c/;'
    Compiling REx 'a*b+c'
    size 9 first at 1
       1: STAR(4)
       2:   EXACT <a>(0)
       4: PLUS(7)
       5:   EXACT <b>(0)
       7: EXACT <c>(9)
       9: END(0)
    floating 'bc' at 0..2147483647 (checking floating) minlen 2
    Guessing start of match, REx 'a*b+c' against 'abc'...
    Found floating substr 'bc' at offset 1...
    Guessed: match at offset 0
    Matching REx 'a*b+c' against 'abc'
      Setting an EVAL scope, savestack=3
       0 <> <abc>           |  1:  STAR
                             EXACT <a> can match 1 times out of 32767...
      Setting an EVAL scope, savestack=3
       1 <a> <bc>           |  4:    PLUS
                             EXACT <b> can match 1 times out of 32767...
      Setting an EVAL scope, savestack=3
       2 <ab> <c>           |  7:      EXACT <c>
       3 <abc> <>           |  9:      END
    Match successful!
    Freeing REx: 'a*b+c'

If you have gotten this far into the tutorial, you can probably guess what the different parts of the debugging output tell you. The first part

このチュートリアルを読み進めてきたのであれば、デバッグ出力の異なる部分が あなたに情報を伝えているのではないかと思うかも知れません。 最初の部分

    Compiling REx 'a*b+c'
    size 9 first at 1
       1: STAR(4)
       2:   EXACT <a>(0)
       4: PLUS(7)
       5:   EXACT <b>(0)
       7: EXACT <c>(9)
       9: END(0)

describes the compilation stage. STAR(4) means that there is a starred object, in this case 'a', and if it matches, goto line 4, i.e., PLUS(7). The middle lines describe some heuristics and optimizations performed before a match:

はコンパイルステージのものです。 STAR(4) は star のついたオブジェクト、この場合は 'a' があって、 それがマッチングした場合には line 4、つまり PLUS(7) へ 移動することを意味しています。 真中の数行はマッチング前の幾つかの発見的手法(heuristics)と 最適化が行われたことを示しています:

    floating 'bc' at 0..2147483647 (checking floating) minlen 2
    Guessing start of match, REx 'a*b+c' against 'abc'...
    Found floating substr 'bc' at offset 1...
    Guessed: match at offset 0

Then the match is executed and the remaining lines describe the process:

その後でマッチングが実行され、残りの行はそのプロセスを説明しています:

    Matching REx 'a*b+c' against 'abc'
      Setting an EVAL scope, savestack=3
       0 <> <abc>           |  1:  STAR
                             EXACT <a> can match 1 times out of 32767...
      Setting an EVAL scope, savestack=3
       1 <a> <bc>           |  4:    PLUS
                             EXACT <b> can match 1 times out of 32767...
      Setting an EVAL scope, savestack=3
       2 <ab> <c>           |  7:      EXACT <c>
       3 <abc> <>           |  9:      END
    Match successful!
    Freeing REx: 'a*b+c'

Each step is of the form n <x> <y>, with <x> the part of the string matched and <y> the part not yet matched. The | 1: STAR says that Perl is at line number 1 in the compilation list above. See "Debugging Regular Expressions" in perldebguts for much more detail.

各ステップは n <x> <y> という形式で、<x> は マッチングした文字列の部分で、<y> はまだマッチングしていない部分です。 | 1: STAR は Perl が先のコンパイルリストの中の行番号 1 の 位置にあることを示しています。 詳細は "Debugging regular expressions" in perldebguts を参照してください。

An alternative method of debugging regexps is to embed print statements within the regexp. This provides a blow-by-blow account of the backtracking in an alternation:

これとは別の正規表現のデバッグ手法は正規表現の中に print 文を 埋め込むことです。 以下の例は選択肢の中のバックトラッキングを逐一数えるものです:

    "that this" =~ m@(?{print "Start at position ", pos, "\n";})
                     t(?{print "t1\n";})
                     h(?{print "h1\n";})
                     i(?{print "i1\n";})
                     s(?{print "s1\n";})
                         |
                     t(?{print "t2\n";})
                     h(?{print "h2\n";})
                     a(?{print "a2\n";})
                     t(?{print "t2\n";})
                     (?{print "Done at position ", pos, "\n";})
                    @x;

prints

以下の出力を行います

    Start at position 0
    t1
    h1
    t2
    h2
    a2
    t2
    Done at position 4

SEE ALSO

This is just a tutorial. For the full story on Perl regular expressions, see the perlre regular expressions reference page.

本ドキュメントはチュートリアルです。 Perl の正規表現に関する完全な説明は正規表現に関する リファレンスページである perlre を参照してください。

For more information on the matching m// and substitution s/// operators, see "Regexp Quote-Like Operators" in perlop. For information on the split operation, see "split" in perlfunc.

マッチング m// や置換 s/// に関するより詳細な情報は "Regexp Quote-Like Operators" in perlop を参照してください。 split 操作に関する情報は "split" in perlfunc を参照してください。

For an excellent all-around resource on the care and feeding of regular expressions, see the book Mastering Regular Expressions by Jeffrey Friedl (published by O'Reilly, ISBN 1556592-257-3).

正規表現に関するすばらしい情報源として Jeffrey Friedl による書籍 Mastering Regular Expressions があります(O'Reillyから出版; ISBN 1556592-257-3)(日本語版は 「詳説 正規表現」ISBN4-87311-130-7 (第二版のもの))。

AUTHOR AND COPYRIGHT

Copyright (c) 2000 Mark Kvale. All rights reserved. Now maintained by Perl porters.

This document may be distributed under the same terms as Perl itself.

Acknowledgments

The inspiration for the stop codon DNA example came from the ZIP code example in chapter 7 of Mastering Regular Expressions.

The author would like to thank Jeff Pinyan, Andrew Johnson, Peter Haworth, Ronald J Kimball, and Joe Smith for all their helpful comments.