5.38.0

NAME

perlre - Perl regular expressions

perlre - Perl の正規表現

説明

This page describes the syntax of regular expressions in Perl.

このページでは Perl での正規表現の構文について説明します。

If you haven't used regular expressions before, a tutorial introduction is available in perlretut. If you know just a little about them, a quick-start introduction is available in perlrequick.

もしこれまでに正規表現を使ったことがないなら、 perlretut にチュートリアルがあります。 正規表現を少しだけ知っているなら、perlrequick に クイックスタートがあります。

Except for "The Basics" section, this page assumes you are familiar with regular expression basics, like what is a "pattern", what does it look like, and how it is basically used. For a reference on how they are used, plus various examples of the same, see discussions of m//, s///, qr// and "??" in "Regexp Quote-Like Operators" in perlop.

"The Basics" 節を例外として、このページは、「パターン」とは何か、 それはどのような見た目のものか、基本的にどのようにして使われるか、といった 正規表現の基本に親しんでいることを仮定しています。 それらをどのように使うのかやそれに関する様々な例に 関しては、"Regexp Quote-Like Operators" in perlop にある m//, s///, qr//, "??" の説明を参照して下さい。

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.

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

基本

Regular expressions are strings with the very particular syntax and meaning described in this document and auxiliary documents referred to by this one. The strings are called "patterns". Patterns are used to determine if some other string, called the "target", has (or doesn't have) the characteristics specified by the pattern. We call this "matching" the target string against the pattern. Usually the match is done by having the target be the first operand, and the pattern be the second operand, of one of the two binary operators =~ and !~, listed in "Binding Operators" in perlop; and the pattern will have been converted from an ordinary string by one of the operators in "Regexp Quote-Like Operators" in perlop, like so:

正規表現とは、この文書と、この文書で参照される補助文書で記述されている、 特定の構文と意味を持つ文字列です。 この文字列は「パターン」と呼ばれます。 パターンは、「ターゲット」と呼ばれる他の文字列が、パターンで指定された 特性を持つ(または持たない)かどうかを判別するために使われます。 これをパターンに対するターゲット文字列の「マッチング」と呼びます。 通常、マッチングは、"Binding Operators" in perlop にリストされている 二つの二項演算子 =~ および !~ の一つの、ターゲットを 最初のオペランドにし、パターンを 2 番目のオペランドにすることによって 行われます; そしてパターンは次のように、"Regexp Quote-Like Operators" in perlop の 演算子の一つによって通常の文字列から変換されています。

 $foo =~ m/abc/

This evaluates to true if and only if the string in the variable $foo contains somewhere in it, the sequence of characters "a", "b", then "c". (The =~ m, or match operator, is described in "m/PATTERN/msixpodualngc" in perlop.)

これは、変数 $foo 内の文字列のどこかに文字並び "a", "b", "c" が 含まれている場合にのみ真と評価されます。 (マッチング演算子 =~ m は、"m/PATTERN/msixpodualngc" in perlop で 説明されています。)

Patterns that aren't already stored in some variable must be delimited, at both ends, by delimiter characters. These are often, as in the example above, forward slashes, and the typical way a pattern is written in documentation is with those slashes. In most cases, the delimiter is the same character, fore and aft, but there are a few cases where a character looks like it has a mirror-image mate, where the opening version is the beginning delimiter, and the closing one is the ending delimiter, like

何らかの変数にまだ格納されていないパターンは、両端が区切り文字で 区切られている必要があります。 これらは上の例のようにスラッシュであることが多く、文書中で パターンを記述する一般的な方法はこれらのスラッシュです。 ほとんどの場合、区切り文字は前と後で同じ文字ですが、文字が鏡像のように 見える場合がいくつかあります; 次のように、開くのが開始区切り文字で、閉じるのが終了区切り文字です:

 $foo =~ m<abc>

Most times, the pattern is evaluated in double-quotish context, but it is possible to choose delimiters to force single-quotish, like

ほとんどの場合、パターンはダブルクォート風コンテキストで評価されますが、 次のように区切り文字を選択してシングルクォート風を強制することもできます:

 $foo =~ m'abc'

If the pattern contains its delimiter within it, that delimiter must be escaped. Prefixing it with a backslash (e.g., "/foo\/bar/") serves this purpose.

パターン内に区切り文字が含まれている場合は、その区切り文字を エスケープする必要があります。 逆スラッシュを前置すると (例えば、"/foo\/bar/")、この目的を 達成できます。

Any single character in a pattern matches that same character in the target string, unless the character is a metacharacter with a special meaning described in this document. A sequence of non-metacharacters matches the same sequence in the target string, as we saw above with m/abc/.

パターン中のすべての単一の文字は、その文字が個々でまたはこの文書で 説明されている特別な意味を持った メタ文字 である場合以外は、 ターゲット文字列内の同じ文字にマッチングします。 非メタ文字の並びは、前述の m/abc/ で見たように、 ターゲット文字列の同じ並びにマッチングします。

Only a few characters (all of them being ASCII punctuation characters) are metacharacters. The most commonly used one is a dot ".", which normally matches almost any character (including a dot itself).

ほんのいくつかの文字 (全て ASCII の句読点文字) がメタ文字です。 もっとも一般的に使われるものはドット "." で、これは通常 (ドット自身を含む) ほとんどの文字にマッチングします。

You can cause characters that normally function as metacharacters to be interpreted literally by prefixing them with a "\", just like the pattern's delimiter must be escaped if it also occurs within the pattern. Thus, "\." matches just a literal dot, "." instead of its normal meaning. This means that the backslash is also a metacharacter, so "\\" matches a single "\". And a sequence that contains an escaped metacharacter matches the same sequence (but without the escape) in the target string. So, the pattern /blur\\fl/ would match any target string that contains the sequence "blur\fl".

文字は "\" で前置されることで通常はメタ文字としての機能を持っている文字を リテラルとして処理させられるようになります; パターンの区切り文字がパターンの中に現れる場合は エスケープされなければならないのと同様です。 従って、"\." は、通常の意味ではなく、 単にリテラルなドット "." にマッチングするようになります。 つまり、逆スラッシュもメタ文字なので、 "\\" は単一の "\" にマッチングするということです。 エスケープされたメタ文字を含む並びは、ターゲット文字列の中の 同じ並び(但しエスケープなし)にマッチングします。 それで、パターン /blur\\fl/ は 並び "blur\fl" を含むターゲット文字列にマッチングします。

The metacharacter "|" is used to match one thing or another. Thus

メタ文字 "|" は二つのもののどちらかをマッチングするのに使われます。 従って:

 $foo =~ m/this|that/

is TRUE if and only if $foo contains either the sequence "this" or the sequence "that". Like all metacharacters, prefixing the "|" with a backslash makes it match the plain punctuation character; in its case, the VERTICAL LINE.

これは $foo に並び "this" または並び "that" のどちらかが 含まれている場合にのみ真になります。 全てのメタ文字と同様、"|" に逆スラッシュを前置すると普通の句読点文字、 この場合は VERTICAL LINE にマッチングします。

 $foo =~ m/this\|that/

is TRUE if and only if $foo contains the sequence "this|that".

これは、$foo"this|that" という並びを含んでいる場合にのみ 真になります。

You aren't limited to just a single "|".

単一の "|" だけに制限されません。

 $foo =~ m/fee|fie|foe|fum/

is TRUE if and only if $foo contains any of those 4 sequences from the children's story "Jack and the Beanstalk".

これは、$foo に童話「ジャックとまめの木」から取った 四つの並びのいずれがを含んでいる場合にのみ真になります。

As you can see, the "|" binds less tightly than a sequence of ordinary characters. We can override this by using the grouping metacharacters, the parentheses "(" and ")".

ここで見られるように、"|" は通常の文字の並びより弱く結びつけます。 これはグループ化メタ文字であるかっこ "("")" を使って 上書きできます。

 $foo =~ m/th(is|at) thing/

is TRUE if and only if $foo contains either the sequence "this thing" or the sequence "that thing". The portions of the string that match the portions of the pattern enclosed in parentheses are normally made available separately for use later in the pattern, substitution, or program. This is called "capturing", and it can get complicated. See "Capture groups".

これは $foo に並び "this thing" または並び "that thing" のいずれかが含まれている場合にのみ TRUE が返されます。 かっこで囲まれたパターンの部分と一致する文字列の部分は、通常、後でパターン、 置換、プログラムで使用するために個別に使用できます。 これは「捕捉」(capturing)と呼ばれ、複雑になる場合があります。 "Capture groups" を参照してください。

The first alternative includes everything from the last pattern delimiter ("(", "(?:" (described later), etc. or the beginning of the pattern) up to the first "|", and the last alternative contains everything from the last "|" to the next closing pattern delimiter. That's why it's common practice to include alternatives in parentheses: to minimize confusion about where they start and end.

最初の代替には最後のパターン区切り ("(", "(?:" (後述) など、または パターンの始まり)から最初の "|" までのすべてが含まれ、 最後の代替には最後の "|" から次の閉じパターン区切りまでが含まれます。 通常代替をかっこの中に入れるのは、その開始位置と終了位置が少しはわかりやすく なるようにです。

Alternatives are tried from left to right, so the first alternative found for which the entire expression matches, is the one that is chosen. This means that alternatives are not necessarily greedy. For example: when matching foo|foot against "barefoot", only the "foo" part will match, as that is the first alternative tried, and it successfully matches the target string. (This might not seem important, but it is important when you are capturing matched text using parentheses.)

代替は左から右へと試されます、なので最初の代替がその完全な式で マッチングしたのならそれが選択されます。 これは代替は貪欲である必要はないということを意味します。 例えば: "barefoot" に対して foo|foot をマッチングさせると、 最初の代替から試されるので、"foo" の部分がマッチングし、 これは対象の文字列に対して成功でマッチングします。 (これは重要ではないでしょうが、かっこを使ってマッチングしたテキストを 捕捉しているときには重要でしょう。)

Besides taking away the special meaning of a metacharacter, a prefixed backslash changes some letter and digit characters away from matching just themselves to instead have special meaning. These are called "escape sequences", and all such are described in perlrebackslash. A backslash sequence (of a letter or digit) that doesn't currently have special meaning to Perl will raise a warning if warnings are enabled, as those are reserved for potential future use.

接頭辞付き逆スラッシュは、メタ文字の特殊な意味を取り除くだけでなく、 一部の文字や数字をそれ自体と一致させないように変更し、 代わりに特殊な意味を持つようにします。 これらは「エスケープシーケンス」と呼ばれ、perlrebackslash で 説明されています。 現在 Perl にとって特殊な意味を持たない (文字や数字の) 逆スラッシュシーケンスは、警告が有効になっている場合に警告を発します; これらは将来使用するために予約されているためです。

One such sequence is \b, which matches a boundary of some sort. \b{wb} and a few others give specialized types of boundaries. (They are all described in detail starting at "\b{}, \b, \B{}, \B" in perlrebackslash.) Note that these don't match characters, but the zero-width spaces between characters. They are an example of a zero-width assertion. Consider again,

そのようなシーケンスのひとつは \b です; これはある種の境界にマッチします。 \b{wb} やその他のいくつかは特定の境界を与えます。 (これらはすべて "\b{}, \b, \B{}, \B" in perlrebackslash で詳細に 記述されています。) これらは文字ではなく、文字と文字の間のゼロ幅の スペースにマッチングすることに注意してください。 これらは ゼロ幅言明 の例です。 もう一度考えてみます:

 $foo =~ m/fee|fie|foe|fum/

It evaluates to TRUE if, besides those 4 words, any of the sequences "feed", "field", "Defoe", "fume", and many others are in $foo. By judicious use of \b (or better (because it is designed to handle natural language) \b{wb}), we can make sure that only the Giant's words are matched:

これは、これら四つの単語以外に、"feed", "field", "Defoe", "fume", その他多くのシーケンスのいずれかが $foo にある場合、TRUE と評価されます。 \b(または(自然言語を処理するように設計されているため) より良い \b{wb})を慎重に使用することで、 確実に巨人の単語だけが一致するようにできます。

 $foo =~ m/\b(fee|fie|foe|fum)\b/
 $foo =~ m/\b{wb}(fee|fie|foe|fum)\b{wb}/

The final example shows that the characters "{" and "}" are metacharacters.

最後の例は、文字 "{""}" がメタ文字であることを示しています。

Another use for escape sequences is to specify characters that cannot (or which you prefer not to) be written literally. These are described in detail in "Character Escapes" in perlrebackslash, but the next three paragraphs briefly describe some of them.

エスケープシーケンスのもう一つの使用法は、文字通りに書くことができない (あるいは書きたくない)文字を指定することです。 これらについては "Character Escapes" in perlrebackslash で詳しく説明していますが、 次の三つの段落でその一部を簡単に説明します。

Various control characters can be written in C language style: "\n" matches a newline, "\t" a tab, "\r" a carriage return, "\f" a form feed, etc.

様々な制御文字は C 言語形式で書くことができます: "\n" は改行にマッチングし、"\t" はタブに、"\r" は復帰に、 "\f" はフォームフィードにといった具合にマッチングします。

More generally, \nnn, where nnn is a string of three octal digits, matches the character whose native code point is nnn. You can easily run into trouble if you don't have exactly three digits. So always use three, or since Perl 5.14, you can use \o{...} to specify any number of octal digits.

より一般的に、\nnn (nnn は 3 桁の 8 進数字) は ネイティブな符号位置が nnn の文字にマッチングします。 正確に 3 桁以外の数字を使うと、簡単に困難に陥ります。 従って、常に 3 桁で使うか、Perl 5.14 以降なら、 任意の桁の 8 進数を使うために \o{...} を使えます。

Similarly, \xnn, where nn are hexadecimal digits, matches the character whose native ordinal is nn. Again, not using exactly two digits is a recipe for disaster, but you can use \x{...} to specify any number of hex digits.

同じように、\xnn (nn は16進数字) はネイティブな数値で nn に なる文字にマッチングします。 再び、正確に 2 桁以外の数字を使うのは災いの元ですが、 任意の桁の 16 進数を指定するために \x{...} を使えます。

Besides being a metacharacter, the "." is an example of a "character class", something that can match any single character of a given set of them. In its case, the set is just about all possible characters. Perl predefines several character classes besides the "."; there is a separate reference page about just these, perlrecharclass.

メタ文字であることに加えて、"." は、特定の集合の任意の 1 文字に マッチングする「文字クラス」の例です。 この場合、集合ははほぼすべての可能な文字です。 Perlは "." 以外にもいくつかの文字クラスを事前定義しています; これらについては、perlrecharclass という別のリファレンスページが あります。

You can define your own custom character classes, by putting into your pattern in the appropriate place(s), a list of all the characters you want in the set. You do this by enclosing the list within [] bracket characters. These are called "bracketed character classes" when we are being precise, but often the word "bracketed" is dropped. (Dropping it usually doesn't cause confusion.) This means that the "[" character is another metacharacter. It doesn't match anything just by itself; it is used only to tell Perl that what follows it is a bracketed character class. If you want to match a literal left square bracket, you must escape it, like "\[". The matching "]" is also a metacharacter; again it doesn't match anything by itself, but just marks the end of your custom class to Perl. It is an example of a "sometimes metacharacter". It isn't a metacharacter if there is no corresponding "[", and matches its literal self:

独自のカスタム文字クラスを定義するには、パターン内の適切な場所に、集合内に 必要なすべての文字のリストを配置します。 これを行うには、リストを [] 大かっこ文字で囲みます。 これらは、正確にであれば「大かっこ文字クラス」と呼ばれますが、 「大かっこ」という単語が削除されることがよくあります。 (通常は、これを削除しても混乱は生じません。) これは、"[" 文字はもう一つのメタ文字であることを意味します。 これ自身だけでは何にもマッチングしません; Perl に対して、後に続くものが大かっこ文字クラスであることを 伝えるためにのみ使用されます。 リテラルの左大かっこにマッチさせたい場合は、"\[" のように エスケープする必要があります。 一致する "]" もメタ文字です; ここでも何にもマッチしませんが、カスタムクラスの終わりを Perl に マークするだけです。 これは「時々メタ文字」の例です。 対応する "[" が存在しない場合はメタ文字ではなく、 リテラルにマッチングします。

 print "]" =~ /]/;  # prints 1

The list of characters within the character class gives the set of characters matched by the class. "[abc]" matches a single "a" or "b" or "c". But if the first character after the "[" is "^", the class instead matches any character not in the list. Within a list, the "-" character specifies a range of characters, so that a-z represents all characters between "a" and "z", inclusive. If you want either "-" or "]" itself to be a member of a class, put it at the start of the list (possibly after a "^"), or escape it with a backslash. "-" is also taken literally when it is at the end of the list, just before the closing "]". (The following all specify the same class of three characters: [-az], [az-], and [a\-z]. All are different from [a-z], which specifies a class containing twenty-six characters, even on EBCDIC-based character sets.)

文字クラスの中の文字のリストは、そのクラスがマッチングする 文字の集合を表しています。 "[abc]" は単一の "a" または "b" または "c" にマッチングします。. しかし、"[" の後の最初の文字が "^" だったときには、その文字クラスは リストの中にない任意の文字にマッチングします。 リストの中では、文字 "-" は文字の範囲を意味します; なので a-z は "a" と "z" を含めてそれらの間にあるすべての文字を表します。 文字クラスの要素として "-" または "]" 自身を使いたい時には、 リストの先頭に (あるいは "^" の後に) 置くか、逆スラッシュを使って エスケープします。 "-" はリストの終端、リストを閉じる "]" の直前にあったときも リテラルとして扱われます。 (次の例はすべて同じ3文字からなる文字クラスです: [-az], [az-], [a\-z]。 これらはすべて EBCDIC ベースの文字集合であっても26文字からなる文字集合 [a-z] とは異なります。)

There is lots more to bracketed character classes; full details are in "Bracketed Character Classes" in perlrecharclass.

大かっこ文字クラスにはもっと色々な要素があります; 完全な詳細は "Bracketed Character Classes" in perlrecharclass にあります。

メタ文字

"The Basics" introduced some of the metacharacters. This section gives them all. Most of them have the same meaning as in the egrep command.

"The Basics" ではメタ文字の一部を導入しました。 この節ではその全てを示します。 そのほとんどは egrep コマンドと同じ意味を持ちます。

Only the "\" is always a metacharacter. The others are metacharacters just sometimes. The following tables lists all of them, summarizes their use, and gives the contexts where they are metacharacters. Outside those contexts or if prefixed by a "\", they match their corresponding punctuation character. In some cases, their meaning varies depending on various pattern modifiers that alter the default behaviors. See "Modifiers".

"\" のみが常にメタ文字です。 その他は時々にだけメタ文字です。 次の表は、すべてのメタ文字の一覧、使用方法の概要、 メタ文字になるコンテキストを示しています。 これらのコンテキスト以外では、または "\" で始まる場合は、 対応する句読点文字とマッチングします。 場合によっては、既定の動作を変更するさまざまなパターン修飾子によって 意味が異なります。 "Modifiers" を参照してください。

            PURPOSE                                  WHERE
 \   Escape the next character                    Always, except when
                                                  escaped by another \
 ^   Match the beginning of the string            Not in []
       (or line, if /m is used)
 ^   Complement the [] class                      At the beginning of []
 .   Match any single character except newline    Not in []
       (under /s, includes newline)
 $   Match the end of the string                  Not in [], but can
       (or before newline at the end of the       mean interpolate a
       string; or before any newline if /m is     scalar
       used)
 |   Alternation                                  Not in []
 ()  Grouping                                     Not in []
 [   Start Bracketed Character class              Not in []
 ]   End Bracketed Character class                Only in [], and
                                                    not first
 *   Matches the preceding element 0 or more      Not in []
       times
 +   Matches the preceding element 1 or more      Not in []
       times
 ?   Matches the preceding element 0 or 1         Not in []
       times
 {   Starts a sequence that gives number(s)       Not in []
       of times the preceding element can be
       matched
 {   when following certain escape sequences
       starts a modifier to the meaning of the
       sequence
 }   End sequence started by {
 -   Indicates a range                            Only in [] interior
 #   Beginning of comment, extends to line end    Only with /x modifier
            目的                                     場所
 \   次の文字をエスケープ                         もう一つの \ で
                                                  エスケープしない限り常に
 ^   文字列(または /m が使われていれば行) の      [] の中以外
       先頭にマッチング
 ^   [] クラスの補集合                            [] の先頭
 .   改行以外の任意の 1 文字にマッチング          [] の中以外
       (/s の下では改行を含む)
 $   文字列の末尾にマッチング                     [] の中以外、しかし
       (または文字列の最後の改行の前;             スカラの変数展開を
       または /m が使われていれば改行の前)        意味する
 |   代替                                         [] の中以外
 ()  グループ化                                   [] の中以外
 [   大かっこ文字クラスの開始                     [] の中以外
 ]   大かっこ文字クラスの終了                     [] のみで先頭以外
 *   前にある要素に 0 回以上マッチング            [] の中以外
 +   前にある要素に 1 回以上マッチング            [] の中以外
 ?   前にある要素に 0 回または 1 回マッチング     [] の中以外
 {   前にある要素がマッチングする回数を指定する   [] の中以外
       並びの開始
 {   以下のいくつかのエスケープシーケンスで
       シーケンスの意味の修飾子の開始
 }   { で開始した並びの終わり
 -   範囲を示す                                   [] の内部のみ
 #   コメントの開始; 行末まで                     /x 修飾子のみ

Notice that most of the metacharacters lose their special meaning when they occur in a bracketed character class, except "^" has a different meaning when it is at the beginning of such a class. And "-" and "]" are metacharacters only at restricted positions within bracketed character classes; while "}" is a metacharacter only when closing a special construct started by "{".

ほとんどのメタ文字は、かっこで囲まれた文字クラス内で出現すると 特殊な意味を失うことに注意してください; ただし、"^" は、そのようなクラスの先頭では異なる意味を持ちます。 また、"-""]" は、かっこ弧で囲まれた文字クラス内の限定された 位置でだけメタ文字になります; 一方、"}" は、"{" によって開始された特殊な構造体を 閉じるときにのみメタ文字です。

In double-quotish context, as is usually the case, you need to be careful about "$" and the non-metacharacter "@". Those could interpolate variables, which may or may not be what you intended.

ダブルクォート風のコンテキストでは、通常の場合と同様、 "$" とメタ文字でない "@" に注意する必要があります。 これらは変数を補完することができますが、それは 意図したものである場合とない場合があります。

These rules were designed for compactness of expression, rather than legibility and maintainability. The "/x and /xx" pattern modifiers allow you to insert white space to improve readability. And use of re 'strict' adds extra checking to catch some typos that might silently compile into something unintended.

これらの規則は、読みやすさや保守性ではなく、表現のコンパクトさを 考慮して設計されています。 "/x and /xx" パターン修飾子を使用すると、読みやすさを 向上させるために空白を挿入できます。 また、re 'strict' を使用すると、 意図しないものに暗黙的にコンパイルされる可能性のあるタイプミスを 捕捉するための追加チェックが追加されます。

By default, the "^" character is guaranteed to match only the beginning of the string, the "$" character only the end (or before the newline at the end), and Perl does certain optimizations with the assumption that the string contains only one line. Embedded newlines will not be matched by "^" or "$". You may, however, wish to treat a string as a multi-line buffer, such that the "^" will match after any newline within the string (except if the newline is the last character in the string), and "$" will match before any newline. At the cost of a little more overhead, you can do this by using the "/m" modifier on the pattern match operator. (Older programs did this by setting $*, but this option was removed in perl 5.10.)

デフォルトでは、文字 "^" は文字列の先頭にのみ、そして文字 "$" は 末尾(または末尾の改行の前)にのみマッチングすることを保証し、そして Perl は 文字列が 1 行のみを含んでいるという仮定でいくつかの最適化を行います。 埋め込まれている改行文字は "^""$" とはマッチングしません。 しかし文字列には複数行が格納されていて、"^" は任意の改行の後(但し 改行文字が文字列の最後の文字だった場合は除く)、そして "$" は任意の改行の 前でマッチングさせたいこともあるでしょう。 小さなオーバーヘッドはありますが、これはパターンマッチングで "/m" 修飾子を使うことで行うことができます。 (古いプログラムでは $* を設定することでこれを行っていましたが これは perl 5.10 では削除されています。)

To simplify multi-line substitutions, the "." character never matches a newline unless you use the /s modifier, which in effect tells Perl to pretend the string is a single line--even if it isn't.

複数行での利用を簡単にするために、文字 "."/s 修飾子を 使って Perl に文字列を 1 行として処理すると Perl に伝えない限り、 改行にはマッチングしません。

修飾子

概要

The default behavior for matching can be changed, using various modifiers. Modifiers that relate to the interpretation of the pattern are listed just below. Modifiers that alter the way a pattern is used by Perl are detailed in "Regexp Quote-Like Operators" in perlop and "Gory details of parsing quoted constructs" in perlop. Modifiers can be added dynamically; see "Extended Patterns" below.

マッチングのデフォルトの振る舞いは、様々な修飾子 (modifier) で 変更できます。 パターンの解釈に関連する修飾子は、直後に一覧にしています。 Perl がパターンを使う方法を変更する 修飾子は "Regexp Quote-Like Operators" in perlop 及び "Gory details of parsing quoted constructs" in perlop に 説明されています。 修飾子は動的に追加できます; 後述する "Extended Patterns" を 参照してください。

m

Treat the string being matched against as multiple lines. That is, change "^" and "$" from matching the start of the string's first line and the end of its last line to matching the start and end of each line within the string.

文字列を複数行としてマッチングするように扱います。 つまり、"^" 及び "$" は文字列の最初の行の先頭および最後の行の末尾に対する マッチングから、文字列中の各行の先頭と末尾に対するマッチングへと 変更されます。

s

Treat the string as single line. That is, change "." to match any character whatsoever, even a newline, which normally it would not match.

文字列を 1 行として扱います。 つまり、"." は任意の 1 文字、通常はマッチングしない改行でさえも マッチングするように変更されます。

Used together, as /ms, they let the "." match any character whatsoever, while still allowing "^" and "$" to match, respectively, just after and just before newlines within the string.

/ms として共に使うと、"^" 及び "$" はそれぞれ 文字列中の改行の直前及び直後のマッチングでありつつ、"." は任意の文字に マッチングするようになります。

i

Do case-insensitive pattern matching. For example, "A" will match "a" under /i.

大文字小文字を区別しないパターンマッチングを行います。 例えば、/i の下では "A" は "a" にマッチングします。

If locale matching rules are in effect, the case map is taken from the current locale for code points less than 255, and from Unicode rules for larger code points. However, matches that would cross the Unicode rules/non-Unicode rules boundary (ords 255/256) will not succeed, unless the locale is a UTF-8 one. See perllocale.

ロケールマッチングルールが有効になっている場合、符号位置 255 以下の場合は 現在のロケールから取られ、より大きい符号位置では Unicode ルールから 取られます。 しかし、Unicode ルールと非 Unicode ルールの境界(番号255/256) を またぐマッチングは、ロケールが UTF-8 のものでない限り成功しません。 perllocale を参照してください。

There are a number of Unicode characters that match a sequence of multiple characters under /i. For example, LATIN SMALL LIGATURE FI should match the sequence fi. Perl is not currently able to do this when the multiple characters are in the pattern and are split between groupings, or when one or more are quantified. Thus

/i の基で複数の文字の並びにマッチングする Unicode 文字はたくさんあります。 例えば、LATIN SMALL LIGATURE FI は並び fi にマッチングするべきです。 複数の文字がパターン中にあってグループ化で分割されている場合、または どれかの文字に量指定子が付いている場合、Perl は今のところこれを行えません。 従って

 "\N{LATIN SMALL LIGATURE FI}" =~ /fi/i;          # Matches
 "\N{LATIN SMALL LIGATURE FI}" =~ /[fi][fi]/i;    # Doesn't match!
 "\N{LATIN SMALL LIGATURE FI}" =~ /fi*/i;         # Doesn't match!
 "\N{LATIN SMALL LIGATURE FI}" =~ /fi/i;          # マッチング
 "\N{LATIN SMALL LIGATURE FI}" =~ /[fi][fi]/i;    # マッチングしない!
 "\N{LATIN SMALL LIGATURE FI}" =~ /fi*/i;         # マッチングしない!
 # The below doesn't match, and it isn't clear what $1 and $2 would
 # be even if it did!!
 "\N{LATIN SMALL LIGATURE FI}" =~ /(f)(i)/i;      # Doesn't match!
 # 次のものはマッチングしないし、もししたとしても $1 と $2 が何になるか
 # はっきりしない!!
 "\N{LATIN SMALL LIGATURE FI}" =~ /(f)(i)/i;      # マッチングしない!

Perl doesn't match multiple characters in a bracketed character class unless the character that maps to them is explicitly mentioned, and it doesn't match them at all if the character class is inverted, which otherwise could be highly confusing. See "Bracketed Character Classes" in perlrecharclass, and "Negation" in perlrecharclass.

Perl は、明示的にマッピングについて言及されていない限り、 大かっこ文字クラスの複数の文字にはマッチングしません; そして文字クラスが否定された場合はそれらには全くマッチングしません; さもなければとても混乱することがあるからです。 "Bracketed Character Classes" in perlrecharclass"Negation" in perlrecharclass を参照して下さい。

x and xx

(xxx)

Extend your pattern's legibility by permitting whitespace and comments. Details in "/x and /xx"

空白やコメントを許可してパターンを読みやすくするように拡張します。 詳細は "/x and /xx" にあります。

p

Preserve the string matched such that ${^PREMATCH}, ${^MATCH}, and ${^POSTMATCH} are available for use after matching.

${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} といったマッチングされた 文字列をマッチングの後も使えるように維持します。

In Perl 5.20 and higher this is ignored. Due to a new copy-on-write mechanism, ${^PREMATCH}, ${^MATCH}, and ${^POSTMATCH} will be available after the match regardless of the modifier.

Perl 5.20 以降ではこれは無視されます。 新しいコピーオンライト機構により、 ${^PREMATCH}, ${^MATCH}, and ${^POSTMATCH} はこの修飾子に関わらず マッチングの後も利用可能です。

a, d, l, and u

(a, d, l, u)

These modifiers, all new in 5.14, affect which character-set rules (Unicode, etc.) are used, as described below in "Character set modifiers".

5.14 から導入されたこれらの新しい修飾子は、どの文字集合規則 (Unicode など) が使われるかに影響を与えます; "Character set modifiers" で後述します。

n

Prevent the grouping metacharacters () from capturing. This modifier, new in 5.22, will stop $1, $2, etc... from being filled in.

グループ化メタ文字 () が捕捉しないようにします。 5.22 からのこの修飾子は、$1, $2 などを埋めるのを止めます。

  "hello" =~ /(hi|hello)/;   # $1 is "hello"
  "hello" =~ /(hi|hello)/n;  # $1 is undef

This is equivalent to putting ?: at the beginning of every capturing group:

これは各捕捉グループの始めに ?: を置くのと等価です:

  "hello" =~ /(?:hi|hello)/; # $1 is undef

/n can be negated on a per-group basis. Alternatively, named captures may still be used.

/n はグループ単位で否定できます。 その代わりに、名前付き捕捉はまだ使えます。

  "hello" =~ /(?-n:(hi|hello))/n;   # $1 is "hello"
  "hello" =~ /(?<greet>hi|hello)/n; # $1 is "hello", $+{greet} is
                                    # "hello"
Other Modifiers

(その他の修飾子)

There are a number of flags that can be found at the end of regular expression constructs that are not generic regular expression flags, but apply to the operation being performed, like matching or substitution (m// or s/// respectively).

一般的な正規表現フラグ ではない ですが、マッチングや置換 (それぞれ m//s///) のような操作が実行される時に適用される 多くのフラグが正規表現構文の末尾に見つけられます。

Flags described further in "Using regular expressions in Perl" in perlretut are:

"Using regular expressions in Perl" in perlretut に さらに記述されているフラグは:

  c  - keep the current position during repeated matching
  g  - globally match the pattern repeatedly in the string

Substitution-specific modifiers described in "s/PATTERN/REPLACEMENT/msixpodualngcer" in perlop are:

置換専用の修飾子で "s/PATTERN/REPLACEMENT/msixpodualngcer" in perlop に記述されているのは:

  e  - evaluate the right-hand side as an expression
  ee - evaluate the right side as a string then eval the result
  o  - pretend to optimize your code, but actually introduce bugs
  r  - perform non-destructive substitution and return the new value

Regular expression modifiers are usually written in documentation as e.g., "the /x modifier", even though the delimiter in question might not really be a slash. The modifiers /imnsxadlup may also be embedded within the regular expression itself using the (?...) construct, see "Extended Patterns" below.

正規表現修飾子は文書中では通常「/x 修飾子」のように記述され、 これは区切りが実際にはスラッシュでなくてもそう記述されます。 また、/imnsxadlup 修飾子は (?...) 構築子を使って正規表現内に 埋め込まれることもあります; 後述する "Extended Patterns" を 参照してください。

一部の修飾子の詳細

Some of the modifiers require more explanation than given in the "Overview" above.

修飾子の一部は前述の "Overview" よりもさらなる説明が必要です。

/x and /xx

(/x/xx)

A single /x tells the regular expression parser to ignore most whitespace that is neither backslashed nor within a bracketed character class, nor within the characters of a multi-character metapattern like (?i: ... ). You can use this to break up your regular expression into more readable parts. Also, the "#" character is treated as a metacharacter introducing a comment that runs up to the pattern's closing delimiter, or to the end of the current line if the pattern extends onto the next line. Hence, this is very much like an ordinary Perl code comment. (You can include the closing delimiter within the comment only if you precede it with a backslash, so be careful!)

単一の /x は、逆スラッシュでエスケープされたり大かっこ文字クラスの中で あったり (?i: ... ) のような複数文字メタパターンの文字の中であったりしない ほとんどの空白を無視するように正規表現パーサに伝えます。 これは正規表現を読みやすく部分に分割するために使えます。 また "#" は、パターンの閉じ区切り文字まで、またはパターンが次の行に 続く場合は現在の行の末尾までのコメントを開始するメタ文字として扱われます。 従って、これは通常の Perl コードのコメントととても似ています。 (コメントの中の閉じ区切り文字は、逆スラッシュを前置した場合にのみ 含めることができます; 注意してください!)

Use of /x means that if you want real whitespace or "#" characters in the pattern (outside a bracketed character class, which is unaffected by /x), then you'll either have to escape them (using backslashes or \Q...\E) or encode them using octal, hex, or \N{} or \p{name=...} escapes. It is ineffective to try to continue a comment onto the next line by escaping the \n with a backslash or \Q.

/x の使用はまた、(/x の影響を受けない大かっこ文字クラス内以外で) パターン中に本当の空白や "#" 文字を使いたい場合は、(逆スラッシュや \Q...\E を使って) エスケープするか、8 進数、16 進数、\N{}, \p{name=...} エスケープの いずれかでエンコードする必要があると言うことです。 \n を逆スラッシュや \Q でエスケープすることで コメントを次の行まで続けようとしても無効です。

You can use "(?#text)" to create a comment that ends earlier than the end of the current line, but text also can't contain the closing delimiter unless escaped with a backslash.

現在の行の末尾より早く修了するコメントを作るために "(?#text)" が使えますが、やはり text は逆スラッシュで エスケープされない限り閉じ区切り文字を含むことはできません。

A common pitfall is to forget that "#" characters (outside a bracketed character class) begin a comment under /x and are not matched literally. Just keep that in mind when trying to puzzle out why a particular /x pattern isn't working as expected. Inside a bracketed character class, "#" retains its non-special, literal meaning.

よくある落とし穴は、(大かっこ文字クラスの外側の) "#" 文字は /x の下ではコメントを始めるので、 文字通りにマッチしないことを忘れてしまうことです。 特定の /x パターンが期待通りに動作しない理由を解明しようとするときには、 このことを念頭に置いてください。 大かっこ文字クラスの中では、"#" は特別でないリテラルな意味のままです。

Starting in Perl v5.26, if the modifier has a second "x" within it, the effect of a single /x is increased. The only difference is that inside bracketed character classes, non-escaped (by a backslash) SPACE and TAB characters are not added to the class, and hence can be inserted to make the classes more readable:

Perl v5.26 以降では、修飾子に二つ目の "x" が含まれている場合、 一つの /x の効果が増加します。 唯一の違いは、大かっこ文字クラスの中では、(逆スラッシュによって) エスケープされていない SPACE および TAB 文字はクラスに追加されません; したがって、クラスをより読みやすくするためにこれらを挿入できます:

    / [d-e g-i 3-7]/xx
    /[ ! @ " # $ % ^ & * () = ? <> ' ]/xx

may be easier to grasp than the squashed equivalents

これは、圧縮された同等物よりも掴みやすいかもしれません:

    /[d-eg-i3-7]/
    /[!@"#$%^&*()=?<>']/

Note that this unfortunately doesn't mean that your bracketed classes can contain comments or extend over multiple lines. A # inside a character class is still just a literal #, and doesn't introduce a comment. And, unless the closing bracket is on the same line as the opening one, the newline character (and everything on the next line(s) until terminated by a ] will be part of the class, just as if you'd written \n.

残念ながら、これはあなたの大かっこクラスがコメントを含めたり 複数行に拡張できたりするということではないことに注意してください。 文字クラスの中の # はリテラルな # のままで、コメントを導入しません。 また、閉じ大かっこが開き大かっこと同じ行にない限り、 改行文字 (および ] で終端されるまでの次の行の全て) は、 \n を書いたのと同じように、クラスの一部になります。

Taken together, these features go a long way towards making Perl's regular expressions more readable. Here's an example:

まとめると、これらの機能は Perl の正規表現をより読みやすくするために 大きく役立ちます。 以下は例です:

    # Delete (most) C comments.
    $program =~ s {
        /\*     # Match the opening delimiter.
        .*?     # Match a minimal number of characters.
        \*/     # Match the closing delimiter.
    } []gsx;

Note that anything inside a \Q...\E stays unaffected by /x. And note that /x doesn't affect space interpretation within a single multi-character construct. For example (?:...) can't have a space between the "(", "?", and ":". Within any delimiters for such a construct, allowed spaces are not affected by /x, and depend on the construct. For example, all constructs using curly braces as delimiters, such as \x{...} can have blanks within but adjacent to the braces, but not elsewhere, and no non-blank space characters. An exception are Unicode properties which follow Unicode rules, for which see "Properties accessible through \p{} and \P{}" in perluniprops.

\Q...\E の内側のものは /x の影響を受けないことに注意してください。 例えば、(?:...)"(", "?", ":" の間にスペースを含むことはできません。 このような構文の区切り文字の中では、スペースが許されるかどうかは /x に影響されず、構文自身に影響されます。 例えば、\x{...} のような、区切り文字として中かっこを使う全ての構文は、 中かっこの隣の内部ではスペース文字を置けますが、他の場所には置けず、 スペース以外の空白文字も置けません。 例外は、Unicode の規則に従っている Unicode 特性です; "Properties accessible through \p{} and \P{}" in perluniprops を 参照してください。

The set of characters that are deemed whitespace are those that Unicode calls "Pattern White Space", namely:

空白と見なされる文字の集合は、Unicode が "Pattern White Space" と 呼ぶもので、次のものです:

 U+0009 CHARACTER TABULATION
 U+000A LINE FEED
 U+000B LINE TABULATION
 U+000C FORM FEED
 U+000D CARRIAGE RETURN
 U+0020 SPACE
 U+0085 NEXT LINE
 U+200E LEFT-TO-RIGHT MARK
 U+200F RIGHT-TO-LEFT MARK
 U+2028 LINE SEPARATOR
 U+2029 PARAGRAPH SEPARATOR

文字集合修飾子

/d, /u, /a, and /l, available starting in 5.14, are called the character set modifiers; they affect the character set rules used for the regular expression.

5.14 から利用可能な /d, /u, /a, /l は文字集合修飾子と呼ばれます; これらは正規表現で使われる文字集合規則に影響を与えます。

The /d, /u, and /l modifiers are not likely to be of much use to you, and so you need not worry about them very much. They exist for Perl's internal use, so that complex regular expression data structures can be automatically serialized and later exactly reconstituted, including all their nuances. But, since Perl can't keep a secret, and there may be rare instances where they are useful, they are documented here.

/d, /u, /l 修飾子はよく使うことはないだろうものなので、 これらについてあまり心配する必要はありません。 これらは Perl の内部仕様のために存在しているので、 複雑な正規表現データ構造は自動的に直列化されて、その後全てのニュアンスを 含めて正確に再構成されます。

The /a modifier, on the other hand, may be useful. Its purpose is to allow code that is to work mostly on ASCII data to not have to concern itself with Unicode.

一方、/a 修飾子は有用かもしれません。 この目的は、Unicode に関して考慮する必要がないように、コードを ほとんど ASCII データとして動作するようにすることです。

Briefly, /l sets the character set to that of whatever Locale is in effect at the time of the execution of the pattern match.

簡単に言うと、/l は、文字集合をパターンマッチングの実行時に有効な ロケール(Locale)に設定します。

/u sets the character set to Unicode.

/u は文字集合を Unicode に設定します。

/a also sets the character set to Unicode, BUT adds several restrictions for ASCII-safe matching.

/a も文字コードを Unicode に設定しますが、 ASCII セーフなマッチングのためにいくつかの制限を加えます。

/d is the old, problematic, pre-5.14 Default character set behavior. Its only use is to force that old behavior.

/d は古くて問題のある、5.14 以前のデフォルト(Default)文字集合の 振る舞いです。 これは古い振る舞いを強制するためだけに使います。

At any given time, exactly one of these modifiers is in effect. Their existence allows Perl to keep the originally compiled behavior of a regular expression, regardless of what rules are in effect when it is actually executed. And if it is interpolated into a larger regex, the original's rules continue to apply to it, and don't affect the other parts.

任意のある瞬間において、これらの修飾子の内正確に一つだけが有効になります。 これにより、 それが実際に実行されるときにどの規則が有効かに関わらず、 Perl が元々コンパイルされた正規表現の振る舞いを保存できるようにします。 そしてそれがより大きな正規表現に展開された場合、元の規則は その部分にだけ適用され続け、他の部分には影響を与えません。

The /l and /u modifiers are automatically selected for regular expressions compiled within the scope of various pragmas, and we recommend that in general, you use those pragmas instead of specifying these modifiers explicitly. For one thing, the modifiers affect only pattern matching, and do not extend to even any replacement done, whereas using the pragmas gives consistent results for all appropriate operations within their scopes. For example,

/l/u の修飾子は、様々なプラグマのスコープ内でコンパイルされた 正規表現で自動的に選択されます; 一般的にはこれらの修飾子を明示的に使うのではなく、これらのプラグマを 使うことを勧めます。 一例を挙げると、修飾子はパターンマッチングに対してのみ影響を与え、 置換には拡張されないことに注意してください; いっぽうプラグマを使うと、そのスコープ内の全ての適切な操作について 一貫した結果となります。 例えば:

 s/foo/\Ubar/il

will match "foo" using the locale's rules for case-insensitive matching, but the /l does not affect how the \U operates. Most likely you want both of them to use locale rules. To do this, instead compile the regular expression within the scope of use locale. This both implicitly adds the /l, and applies locale rules to the \U. The lesson is to use locale, and not /l explicitly.

これは大文字小文字マッチングにロケールの規則を使って "foo" に マッチングしますが、/l\U がどう処理を行うかに影響を与えません。 あなたはほぼ確実にこれら二つにロケールの規則を使うことを臨むはずです。 これをするためには、代わりに use locale のスコープ内で正規表現をコンパイルします。 これらは両方とも暗黙に /l を追加し、\U にロケールの規則を適用します。 ここで学ぶべきことは、use locale を使って、明示的に /l を 使わないことです。

Similarly, it would be better to use use feature 'unicode_strings' instead of,

同様に、Unicode の規則にするには次のようにする代わりに use feature 'unicode_strings' を使った方が良いです:

 s/foo/\Lbar/iu

to get Unicode rules, as the \L in the former (but not necessarily the latter) would also use Unicode rules.

前者の \L (しかし後者は必要ではないです) も Unicode の規則を 使うからです。

More detail on each of the modifiers follows. Most likely you don't need to know this detail for /l, /u, and /d, and can skip ahead to /a.

それぞれの修飾子に関するさらなる詳細は後述します。 ほとんど確実にあなたは /l, /u, /d の詳細を知る必要はなく、 /a まで読み飛ばせます。

/l

means to use the current locale's rules (see perllocale) when pattern matching. For example, \w will match the "word" characters of that locale, and "/i" case-insensitive matching will match according to the locale's case folding rules. The locale used will be the one in effect at the time of execution of the pattern match. This may not be the same as the compilation-time locale, and can differ from one match to another if there is an intervening call of the setlocale() function.

これはパターンマッチングのときに現在のロケールの規則 (perllocale 参照) を 使うことを意味します。 例えば、\w はこのロケールの「単語」文字にマッチングし、 "/i" の大文字小文字マッチングは、現在のロケールの大文字小文字畳み込み規則に 従ってマッチングします。 使われるロケールはパターンマッチングが実行される時点で有効なものです。 これはコンパイル時のロケールと同じではないかもしれませんし、 setlocale() 関数 の呼び出しが間に入ると、呼び出し毎に異なることもあります。

Prior to v5.20, Perl did not support multi-byte locales. Starting then, UTF-8 locales are supported. No other multi byte locales are ever likely to be supported. However, in all locales, one can have code points above 255 and these will always be treated as Unicode no matter what locale is in effect.

v5.20 より前では、Perl は複数バイトロケールに対応していませんでした。 v5.20 から、UTF-8 ロケールに対応しました。 他の複数バイトロケールに対応することはおそらくありません。 しかし、全てのロケールで、255 を越える符号位置を保持することができ、 これはどのロケールが有効であるかに関わらず常に Unicode として扱われます。

Under Unicode rules, there are a few case-insensitive matches that cross the 255/256 boundary. Except for UTF-8 locales in Perls v5.20 and later, these are disallowed under /l. For example, 0xFF (on ASCII platforms) does not caselessly match the character at 0x178, LATIN CAPITAL LETTER Y WITH DIAERESIS, because 0xFF may not be LATIN SMALL LETTER Y WITH DIAERESIS in the current locale, and Perl has no way of knowing if that character even exists in the locale, much less what code point it is.

Unicode の規則の基では、255/256 の境界をまたぐ大文字小文字を無視した マッチングがいくつかあります。 Perl v5.20 以降での UTF-8 ロケールを除いて、 これらは /l の基では認められません。 例えば、(ASCII プラットフォームで) 0xFF は 0x178, LATIN CAPITAL LETTER Y WITH DIAERESIS と大文字小文字を無視した マッチングをしません; なぜなら 0xFF は現在のロケールでは LATIN SMALL LETTER Y WITH DIAERESIS ではないかもしれず、Perl は このロケールでこの文字があるかどうかすら知る方法がなく、ましてや これがどの符号位置かを知る方法もないからです。

In a UTF-8 locale in v5.20 and later, the only visible difference between locale and non-locale in regular expressions should be tainting, if your perl supports taint checking (see perlsec).

v5.20 以降の UTF-8 ロケールでは、 正規表現でのロケールと非ロケールの目に見える唯一の違いは、 perl が汚染チェックに対応している場合の汚染だけのはずです (perlsec 参照)。

This modifier may be specified to be the default by use locale, but see "Which character set modifier is in effect?".

この修飾子は use locale によってデフォルトで設定されますが、 "Which character set modifier is in effect?" を参照してください。

/u

means to use Unicode rules when pattern matching. On ASCII platforms, this means that the code points between 128 and 255 take on their Latin-1 (ISO-8859-1) meanings (which are the same as Unicode's). (Otherwise Perl considers their meanings to be undefined.) Thus, under this modifier, the ASCII platform effectively becomes a Unicode platform; and hence, for example, \w will match any of the more than 100_000 word characters in Unicode.

これはパターンマッチングのときに Unicode の規則を使うことを意味します。 ASCII プラットフォームでは、これは符号位置 128 から 255 は Latin-1 (ISO-8859-1) という意味になります (これは Unicode と同じです)。 (さもなければ Perl はこれらの意味は未定義として扱います。) 従って、この修飾子の基では、ASCII プラットフォームは 事実上 Unicode プラットフォームになります; 従って、 例えば、\w は Unicode の 100,000 以上の単語文字のどれにも マッチングします。

Unlike most locales, which are specific to a language and country pair, Unicode classifies all the characters that are letters somewhere in the world as \w. For example, your locale might not think that LATIN SMALL LETTER ETH is a letter (unless you happen to speak Icelandic), but Unicode does. Similarly, all the characters that are decimal digits somewhere in the world will match \d; this is hundreds, not 10, possible matches. And some of those digits look like some of the 10 ASCII digits, but mean a different number, so a human could easily think a number is a different quantity than it really is. For example, BENGALI DIGIT FOUR (U+09EA) looks very much like an ASCII DIGIT EIGHT (U+0038), and LEPCHA DIGIT SIX (U+1C46) looks very much like an ASCII DIGIT FIVE (U+0035). And, \d+, may match strings of digits that are a mixture from different writing systems, creating a security issue. A fraudulent website, for example, could display the price of something using U+1C46, and it would appear to the user that something cost 500 units, but it really costs 600. A browser that enforced script runs ("Script Runs") would prevent that fraudulent display. "num()" in Unicode::UCD can also be used to sort this out. Or the /a modifier can be used to force \d to match just the ASCII 0 through 9.

特定の言語と国に固有であるほとんどのロケールと異なり、 Unicode は世界の どこか で字(letter)として扱われている全ての 文字(character)を \w に分類します。 例えば、あなたのロケールは (あなたがたまたまアイスランド語を話さない限り) LATIN SMALL LETTER ETH を字として考えないかもしれません。 同様に、世界のどこかで数字である全ての文字は \d にマッチングします; これは 10 ではなく 100 のマッチングの可能性があります。 さらにこれらの数字の一部は 10 の ASCII 数字と似ていますが、 異なる数字を意味するため、人間はその数字が実際と異なる量であると 簡単に考えてしまいます。 例えば、 BENGALI DIGIT FOUR (U+09EA) は ASCII DIGIT EIGHT (U+0038) に とてもよく似ていて、 LEPCHA DIGIT SIX (U+1C46) は ASCII DIGIT FIVE (U+0035) に とてもよく似ています。 \d+ は、異なる記法から混ぜた数字の文字列にマッチングするので、 セキュリティ上の問題を作ります。 例えば、詐欺サイトは、何か U+1C46 を使った価格を表示し、 何か 500 ユニットのコストであるかのようにユーザーに見えるけれども、 実際のコストは 600 にできます。 用字連続 ("Script Runs") を矯正するブラウザはこのような 詐欺的な表示を防ぎます。 これを整理するために "num()" in Unicode::UCD も使えます。 あるいは /a 修飾子は、\d が単に ASCII の 0 から 9 に マッチングすることを強制するために使えます。

Also, under this modifier, case-insensitive matching works on the full set of Unicode characters. The KELVIN SIGN, for example matches the letters "k" and "K"; and LATIN SMALL LIGATURE FF matches the sequence "ff", which, if you're not prepared, might make it look like a hexadecimal constant, presenting another potential security issue. See https://unicode.org/reports/tr36 for a detailed discussion of Unicode security issues.

また、この修飾子の基では、大文字小文字を無視したマッチングは Unicode の 完全な集合で動作します。 例えば KELVIN SIGN は "k" と "K" にマッチングします; LATIN SMALL LIGATURE FF は、準備していなければ 16 進数定数のように 見えるかもしれない並び "ff" にマッチングし、もう一つの潜在的な セキュリティ問題になります。 Unicode のセキュリティ問題に関する詳細な議論については https://unicode.org/reports/tr36 を参照してください。

This modifier may be specified to be the default by use feature 'unicode_strings, use locale ':not_characters', or use v5.12 (or higher), but see "Which character set modifier is in effect?".

この修飾子は use feature 'unicode_strings, use locale ':not_characters', use v5.12 (またはそれ以上) によってデフォルトに 設定されますが、"Which character set modifier is in effect?" を 参照してください。

/d

IMPORTANT: Because of the unpredictable behaviors this modifier causes, only use it to maintain weird backward compatibilities. Use the unicode_strings feature in new code to avoid inadvertently enabling this modifier by default.

重要: この修飾子が引き起こす予測できない振る舞いのため、 おかしな後方互換性を維持するためだけに使ってください。 不注意でこの修飾子をデフォルトで有効にすることを避けるために、 新しいコードでは unicode_strings 機能を 使ってください。

What does this modifier do? It "Depends"!

この修飾子は何をするのでしょう? 「場合によります」!

This modifier means to use platform-native matching rules except when there is cause to use Unicode rules instead, as follows:

この修飾子は、以下のように Unicode の規則が使われる場合を除いて、 プラットフォームにネイティブな規則を使うことを意味します:

  1. the target string's UTF8 flag (see below) is set; or

    ターゲット文字列の UTF8 フラグ が 設定されている; または

  2. the pattern's UTF8 flag (see below) is set; or

    パターンの UTF8 フラグ が 設定されている; または

  3. the pattern explicitly mentions a code point that is above 255 (say by \x{100}); or

    パターンが、(\x{100} のような形で)255 を超える符号位置に明示的に 言及している; または

  4. the pattern uses a Unicode name (\N{...}); or

    パターンが Unicode 名 (\N{...}) を使っている; または

  5. the pattern uses a Unicode property (\p{...} or \P{...}); or

    パターンが Unicode 特性 (\p{...}) や \P{...}) を使っている; または

  6. the pattern uses a Unicode break (\b{...} or \B{...}); or

    パターンが Unicode 単語境界 (\b{...} または \B{...}) を使っている; または

  7. the pattern uses "(?[ ])"

    パターンが "(?[ ])" を使っている

  8. the pattern uses (*script_run: ...)

    パターンが (*script_run: ...) を使っている

Regarding the "UTF8 flag" references above: normally Perl applications shouldn't think about that flag. It's part of Perl's internals, so it can change whenever Perl wants. /d may thus cause unpredictable results. See "The "Unicode Bug"" in perlunicode. This bug has become rather infamous, leading to yet other (without swearing) names for this modifier like "Dicey" and "Dodgy".

前述の "UTF8 フラグ" について: 通常 Perl のアプリケーションは このフラグについて考えるべきではありません。 これは Perl の内部の一部で、Perl が望むときはいつでも変更されます。 従って、/d は予測不能な結果になるかもしれません。 "The "Unicode Bug"" in perlunicode を参照してください。 このバグは、悪名高くなり、この修飾子のもう一つの(罵りのない) "Dicey" と "Dodgy" のような名前を引き起こしています。

Here are some examples of how that works on an ASCII platform:

以下は ASCII プラットフォームでどのように動作するかの例です:

 $str =  "\xDF";        #
 utf8::downgrade($str); # $str is not UTF8-flagged.
 $str =~ /^\w/;         # No match, since no UTF8 flag.

 $str .= "\x{0e0b}";    # Now $str is UTF8-flagged.
 $str =~ /^\w/;         # Match! $str is now UTF8-flagged.
 chop $str;
 $str =~ /^\w/;         # Still a match! $str retains its UTF8 flag.

Under Perl's default configuration this modifier is automatically selected by default when none of the others are, so yet another name for it (unfortunately) is "Default".

Perl のデフォルト設定では、この修飾子は他のものが指定されなかった場合に デフォルトとして自動的に選択されるので、これのもう一つの名前は (残念ながら) "Default" です。

Whenever you can, use the unicode_strings to cause to be the default instead.

使えるときはいつでも、代わりに がデフォルトになるように、 unicode_strings を 使ってください。

/a (と /aa)

This modifier stands for ASCII-restrict (or ASCII-safe). This modifier may be doubled-up to increase its effect.

この修飾子は ASCII 制限 (あるいは ASCII セーフ) を意味します。 この修飾子は、2 倍にすることで効果が増します。

When it appears singly, it causes the sequences \d, \s, \w, and the Posix character classes to match only in the ASCII range. They thus revert to their pre-5.6, pre-Unicode meanings. Under /a, \d always means precisely the digits "0" to "9"; \s means the five characters [ \f\n\r\t], and starting in Perl v5.18, the vertical tab; \w means the 63 characters [A-Za-z0-9_]; and likewise, all the Posix classes such as [[:print:]] match only the appropriate ASCII-range characters.

これが単体で使われると、\d, \s, \w, Posix 文字クラスは ASCII の範囲のみにマッチングするようになります。 従って、これらは 5.6 以前の、Unicode 以前の意味に戻します。 /a の基では、\d は常に正確に数字 "0" から "9" を意味します; \s[ \f\n\r\t] の 5 文字、および Perl v5.18 から垂直タブ、 を意味します; \w[A-Za-z0-9_] の 63 文字を意味します; 同様に、[[:print:]] のような全ての Posix クラスは 適切な ASCII の範囲の文字にのみマッチングします。

This modifier is useful for people who only incidentally use Unicode, and who do not wish to be burdened with its complexities and security concerns.

この修飾子は、偶然 Unicode を使っている人々で、その複雑さと セキュリティの問題に関する重荷を背負いたくない人々にとっては有用です。

With /a, one can write \d with confidence that it will only match ASCII characters, and should the need arise to match beyond ASCII, you can instead use \p{Digit} (or \p{Word} for \w). There are similar \p{...} constructs that can match beyond ASCII both white space (see "Whitespace" in perlrecharclass), and Posix classes (see "POSIX Character Classes" in perlrecharclass). Thus, this modifier doesn't mean you can't use Unicode, it means that to get Unicode matching you must explicitly use a construct (\p{}, \P{}) that signals Unicode.

/a を使うと、ASCII 文字だけにマッチングすることに自信を持って 書くことができ、ASCII を超えてマッチングする必要が発生したときには、 代わりに \p{Digit} (または \w として \p{Word}) が使えます。 ASCII を超えたスペース ("Whitespace" in perlrecharclass を参照してください) と Posix クラス ("POSIX Character Classes" in perlrecharclass を 参照してください) の両方にマッチングする似たような \p{...} 構文があります。 従って、この修飾子は Unicode が使えなくなるということではなく、 Unicode のマッチングには明示的に Unicode を意味する構文 (\p{}, \P{}) を使わないといけないということです。

As you would expect, this modifier causes, for example, \D to mean the same thing as [^0-9]; in fact, all non-ASCII characters match \D, \S, and \W. \b still means to match at the boundary between \w and \W, using the /a definitions of them (similarly for \B).

予想できるとおり、 この修飾子は、例えば、\D[^0-9] と 同じことにします; 実際、全ての非 ASCII 文字は \D, \S, \W にマッチングします。 \b はまだ \w\W の境界にマッチングします; これらのために (\B と同様) /a の定義を使います。

Otherwise, /a behaves like the /u modifier, in that case-insensitive matching uses Unicode rules; for example, "k" will match the Unicode \N{KELVIN SIGN} under /i matching, and code points in the Latin1 range, above ASCII will have Unicode rules when it comes to case-insensitive matching.

さもなければ、/a/u 修飾子のように振る舞います; 大文字小文字を無視したマッチングには Unicode の規則を使います; 例えば、"k" は /i の基では \N{KELVIN SIGN} にマッチングし、 ASCII の範囲を超える Latin1 の範囲の符号位置は、大文字小文字を無視した マッチングで使われる場合は Unicode の規則を使います。

To forbid ASCII/non-ASCII matches (like "k" with \N{KELVIN SIGN}), specify the "a" twice, for example /aai or /aia. (The first occurrence of "a" restricts the \d, etc., and the second occurrence adds the /i restrictions.) But, note that code points outside the ASCII range will use Unicode rules for /i matching, so the modifier doesn't really restrict things to just ASCII; it just forbids the intermixing of ASCII and non-ASCII.

("k" と \N{KELVIN SIGN} のような) ASCII/非-ASCII マッチングを禁止するには、 /aai/aia のように "a" を 2 回指定します。 (最初の "a"\d などを制限し、2 番目は /i の制限を追加します。) しかし、 ASCII の範囲外の符号位置は /i マッチングに Unicode 規則を 使うので、この修飾子は実際には単に ASCII に制限するものではないことに 注意してください; これは単に ASCII と非 ASCII を混ぜることを禁止します。

To summarize, this modifier provides protection for applications that don't wish to be exposed to all of Unicode. Specifying it twice gives added protection.

まとめると、この修飾子は全ての Unicode に対して曝されることを望んでいない アプリケーションに対する保護を提供します。 2 回指定することで追加の保護を提供します。

This modifier may be specified to be the default by use re '/a' or use re '/aa'. If you do so, you may actually have occasion to use the /u modifier explicitly if there are a few regular expressions where you do want full Unicode rules (but even here, it's best if everything were under feature "unicode_strings", along with the use re '/aa'). Also see "Which character set modifier is in effect?".

この修飾子は use re '/a' または use re '/aa' でデフォルトに 設定されます。 そうすると、もし完全な Unicode 規則を使いたい正規表現がある場合は、 /u 修飾子を明示的に使う機会があるかもしれません (その場合でも、全てが "unicode_strings" の基なら、 use re '/aa' と共にするのが最良です)。 "Which character set modifier is in effect?" も参照してください。

どの文字集合修飾子が有効?

Which of these modifiers is in effect at any given point in a regular expression depends on a fairly complex set of interactions. These have been designed so that in general you don't have to worry about it, but this section gives the gory details. As explained below in "Extended Patterns" it is possible to explicitly specify modifiers that apply only to portions of a regular expression. The innermost always has priority over any outer ones, and one applying to the whole expression has priority over any of the default settings that are described in the remainder of this section.

ある正規表現のあるポイントでどの修飾子が有効かは、かなり複雑な相互作用に 依存します。 これらは、基本的にはあなたがこれらについて心配しなくて良いように 設計されています。 しかし、この節は詳細を記述します。 "Extended Patterns" で後述するとおり、正規表現の一部にだけ 適用する修飾子を明示的に指定することが可能です。 一番内側のものは常により外側のものより優先され、式全体に適用されるものは この節の残りで記述されるデフォルト設定より優先されます。

The use re '/foo' pragma can be used to set default modifiers (including these) for regular expressions compiled within its scope. This pragma has precedence over the other pragmas listed below that also change the defaults.

use re '/foo' プラグマは、 このスコープ内でコンパイルされる正規表現に対して(これらを含む) デフォルトの修飾子を設定するのに使えます。 このプラグマは、デフォルトを変更する後述するその他のプラグマに優先します。

Otherwise, use locale sets the default modifier to /l; and use feature 'unicode_strings, or use v5.12 (or higher) set the default to /u when not in the same scope as either use locale or use bytes. (use locale ':not_characters' also sets the default to /u, overriding any plain use locale.) Unlike the mechanisms mentioned above, these affect operations besides regular expressions pattern matching, and so give more consistent results with other operators, including using \U, \l, etc. in substitution replacements.

さもなければ、use locale はデフォルト修飾子を /l に 設定します; そして、use feature 'unicode_stringsuse v5.12 (またはそれ以上) は、 同じスコープに use localeuse bytes が なければ、デフォルトを /u に設定します。 (use locale ':not_characters' はまた デフォルトを /u に設定し、普通の use locale を上書きします。) 前述した機構と異なり、これらは正規表現パターンマッチング以外の操作に 影響するので、置換での \U, \l を使うことを含むその他の操作と より一貫性のある結果になります。

If none of the above apply, for backwards compatibility reasons, the /d modifier is the one in effect by default. As this can lead to unexpected results, it is best to specify which other rule set should be used.

前述のどれも適用されない場合、後方互換性のために、 /d 修飾子がデフォルトで有効になります。 これは想定外の結果になることがあるので、 その他の規則集合が使われるように指定するのが最良です。

Perl 5.14 より前の文字集合修飾子の振る舞い

Prior to 5.14, there were no explicit modifiers, but /l was implied for regexes compiled within the scope of use locale, and /d was implied otherwise. However, interpolating a regex into a larger regex would ignore the original compilation in favor of whatever was in effect at the time of the second compilation. There were a number of inconsistencies (bugs) with the /d modifier, where Unicode rules would be used when inappropriate, and vice versa. \p{} did not imply Unicode rules, and neither did all occurrences of \N{}, until 5.12.

5.14 より前では、明示的な修飾子はありませんが、 use locale のスコープ内でコンパイルされた正規表現に関しては /l が仮定され、さもなければ /d が仮定されます。 しかし、ある正規表現をより大きな正規表現に展開した場合、元のコンパイル時の 状況は、2 回目のコンパイル時点で有効なもので上書きされます。 /d 演算子には、不適切なときに Unicode 規則が使われる、あるいはその逆の 多くの非一貫性(バグ)があります。 \p{} および \N{} は 5.12 まで Unicode 規則を仮定していません。

正規表現

量指定子

Quantifiers are used when a particular portion of a pattern needs to match a certain number (or numbers) of times. If there isn't a quantifier the number of times to match is exactly one. The following standard quantifiers are recognized:

Quantifiers are used when a particular portion of a pattern needs to match a certain number (or numbers) of times. If there isn't a quantifier the number of times to match is exactly one. 以下の標準的な量指定子を使えます:

    *           Match 0 or more times
    +           Match 1 or more times
    ?           Match 1 or 0 times
    {n}         Match exactly n times
    {n,}        Match at least n times
    {,n}        Match at most n times
    {n,m}       Match at least n but not more than m times
    *           0 回以上マッチング
    +           1 回以上マッチング
    ?           0 回または 1 回マッチング
    {n}         正確に n 回マッチング
    {n,}        最低 n 回マッチング
    {,n}        最大 n 回マッチング
    {n,m}       n 回以上 m 回以下マッチング

(If a non-escaped curly bracket occurs in a context other than one of the quantifiers listed above, where it does not form part of a backslashed sequence like \x{...}, it is either a fatal syntax error, or treated as a regular character, generally with a deprecation warning raised. To escape it, you can precede it with a backslash ("\{") or enclose it within square brackets ("[{]"). This change will allow for future syntax extensions (like making the lower bound of a quantifier optional), and better error checking of quantifiers).

(前述した量指定子の一つ以外のコンテキストでエスケープされない中かっこが 使われて、\x{...} のような逆スラッシュ付き並びの一部ではないときには、 普通の文字として扱われるか、致命的エラーになり、どちらでも 一般的には廃止予定警告が発生します。 これをエスケープするには、逆スラッシュを前置したり ("\{") 大かっこで囲んだり ("[{]") できます。 この変更により、(量指定子の加減をオプションにするような) 将来の 文法の拡張ができるようになり、量指定子のより良いエラーチェックが できるようになります。

The "*" quantifier is equivalent to {0,}, the "+" quantifier to {1,}, and the "?" quantifier to {0,1}. n and m are limited to non-negative integral values less than a preset limit defined when perl is built. This is usually 65534 on the most common platforms. The actual limit can be seen in the error message generated by code such as this:

"*" 量指定子は {0,} と、"+" 量指定子は {1,} と、 "?" 量指定子は {0,1} と等価です。 nm は perl をビルドしたときに定義した既定の制限より小さな 非負整数回に制限されます。 これは大抵のプラットフォームでは 65534 回になっています。 実際の制限は次のようなコードを実行すると生成されるエラーメッセージで 見ることができます:

    $_ **= $_ , / {$_} / for 2 .. 42;

By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier with a "?". Note that the meanings don't change, just the "greediness":

デフォルトでは、パターンで行われる量指定は「貪欲」です; つまりそれはパターンの残りの部分が可能な範囲で、 (始めた地点から)可能な限り多くを先にあるパターンでマッチングさせます。 もし最小回数でのマッチングを行いたいのであれば、量指定子の後ろに "?" を続けます。 意味は変更されずに「貪欲さ」だけを変更できます:

    *?        Match 0 or more times, not greedily
    +?        Match 1 or more times, not greedily
    ??        Match 0 or 1 time, not greedily
    {n}?      Match exactly n times, not greedily (redundant)
    {n,}?     Match at least n times, not greedily
    {,n}?     Match at most n times, not greedily
    {n,m}?    Match at least n but not more than m times, not greedily
    *?        0 回以上の貪欲でないマッチング
    +?        1 回以上の貪欲でないマッチング
    ??        0 回または 1 回の貪欲でないマッチング
    {n}?      ちょうど n 回の貪欲でないマッチング (冗長)
    {n,}?     n 回以上の貪欲でないマッチング
    {,n}?     最大 n 回の貪欲でないマッチング
    {n,m}?    n 回以上 m 回以下の貪欲でないマッチング

Normally when a quantified subpattern does not allow the rest of the overall pattern to match, Perl will backtrack. However, this behaviour is sometimes undesirable. Thus Perl provides the "possessive" quantifier form as well.

通常、パターンのうちの量指定された一部によってパターン全体が マッチングに失敗したとき、Perl はバックトラックを行います。 しかしこの振る舞いは望まれないこともあります。 そのため、Perl は「絶対最大(possessive)」量指定形式も提供しています。

 *+     Match 0 or more times and give nothing back
 ++     Match 1 or more times and give nothing back
 ?+     Match 0 or 1 time and give nothing back
 {n}+   Match exactly n times and give nothing back (redundant)
 {n,}+  Match at least n times and give nothing back
 {,n}+  Match at most n times and give nothing back
 {n,m}+ Match at least n but not more than m times and give nothing back
 *+        0 回以上マッチングして何も返さない
 ++        1 回以上マッチングして何も返さない
 ?+        0 回または 1 回マッチングして何も返さない
 {n}+      ちょうど n 回のマッチングして何も返さない (冗長)
 {n,}+     n 回以上のマッチングして何も返さない
 {,n}+     最大 n 回のマッチングして何も返さない
 {n,m}+    n 回以上 m 回以下マッチングして何も返さない

For instance,

例えば、

   'aaaa' =~ /a++a/

will never match, as the a++ will gobble up all the "a"'s in the string and won't leave any for the remaining part of the pattern. This feature can be extremely useful to give perl hints about where it shouldn't backtrack. For instance, the typical "match a double-quoted string" problem can be most efficiently performed when written as:

は、a++ が文字列中の全ての "a" を飲み込んでしまい、 後に何も残さないためマッチングしません。 この機能はバックトラックするべきでない場所のヒントを perl に 与えるのに非常に便利です。 例えば、典型的な「ダブルクォート文字列のマッチング」問題で次のように 書くととても効率的になります:

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

as we know that if the final quote does not match, backtracking will not help. See the independent subexpression "(?>pattern)" for more details; possessive quantifiers are just syntactic sugar for that construct. For instance the above example could also be written as follows:

見ての通り最後のクォートがマッチングしなかったとき、バックトラックは 役に立ちません。 詳細は独立したサブパターン "(?>pattern)" を参照してください; 絶対最大量指定子はまさにその構文糖です。 例えばこの例は次のようにも書けます:

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

Note that the possessive quantifier modifier can not be combined with the non-greedy modifier. This is because it would make no sense. Consider the follow equivalency table:

絶対最大量指定修飾子は非貪欲修飾子と結合できないことに注意してください。 これは無意味だからです。 次の等価性表を考慮してください:

    Illegal         Legal
    ------------    ------
    X??+            X{0}
    X+?+            X{1}
    X{min,max}?+    X{min}

エスケープシーケンス

Because patterns are processed as double-quoted strings, the following also work:

パターンはダブルクォート文字列として処理されるため、 以下のエスケープ文字も動作します:

 \t          tab                   (HT, TAB)
 \n          newline               (LF, NL)
 \r          return                (CR)
 \f          form feed             (FF)
 \a          alarm (bell)          (BEL)
 \e          escape (think troff)  (ESC)
 \cK         control char          (example: VT)
 \x{}, \x00  character whose ordinal is the given hexadecimal number
 \N{name}    named Unicode character or character sequence
 \N{U+263D}  Unicode character     (example: FIRST QUARTER MOON)
 \o{}, \000  character whose ordinal is the given octal number
 \l          lowercase next char (think vi)
 \u          uppercase next char (think vi)
 \L          lowercase until \E (think vi)
 \U          uppercase until \E (think vi)
 \Q          quote (disable) pattern metacharacters until \E
 \E          end either case modification or quoted section, think vi
 \t          タブ                  (水平タブ;HT、TAB)
 \n          改行                  (LF、NL)
 \r          復帰                  (CR)
 \f          フォームフィード      (FF)
 \a          アラーム (ベル)       (BEL)
 \e          エスケープ (troff 的) (ESC)
 \cK         制御文字              (例: VT)
 \x{}, \x00  16 進数で番号指定された文字
 \N{name}    名前付きユニコード文字または文字並び
 \N{U+263D}  Unicode 文字          (例: FIRST QUARTER MOON)
 \o{}, \000  8 進数で番号指定された文字
 \l          次の文字を小文字に (vi 的)
 \u          次の文字を大文字に (vi 的)
 \L          \E まで小文字に (vi 的)
 \U          \E まで大文字に (vi 的)
 \Q          \E までパターンメタ文字の無効化(Quote)
 \E          大文字小文字変更またはクォートの終端 (vi 的)

詳細は "Quote and Quote-like Operators" in perlop にあります。

文字クラス及び他の特殊なエスケープ

In addition, Perl defines the following:

さらに、Perl は以下のものを定義します:

 Sequence   Note    Description
  [...]     [1]  Match a character according to the rules of the
                   bracketed character class defined by the "...".
                   Example: [a-z] matches "a" or "b" or "c" ... or "z"
  [[:...:]] [2]  Match a character according to the rules of the POSIX
                   character class "..." within the outer bracketed
                   character class.  Example: [[:upper:]] matches any
                   uppercase character.
  (?[...])  [8]  Extended bracketed character class
  \w        [3]  Match a "word" character (alphanumeric plus "_", plus
                   other connector punctuation chars plus Unicode
                   marks)
  \W        [3]  Match a non-"word" character
  \s        [3]  Match a whitespace character
  \S        [3]  Match a non-whitespace character
  \d        [3]  Match a decimal digit character
  \D        [3]  Match a non-digit character
  \pP       [3]  Match P, named property.  Use \p{Prop} for longer names
  \PP       [3]  Match non-P
  \X        [4]  Match Unicode "eXtended grapheme cluster"
  \1        [5]  Backreference to a specific capture group or buffer.
                   '1' may actually be any positive integer.
  \g1       [5]  Backreference to a specific or previous group,
  \g{-1}    [5]  The number may be negative indicating a relative
                   previous group and may optionally be wrapped in
                   curly brackets for safer parsing.
  \g{name}  [5]  Named backreference
  \k<name>  [5]  Named backreference
  \k'name'  [5]  Named backreference
  \k{name}  [5]  Named backreference
  \K        [6]  Keep the stuff left of the \K, don't include it in $&
  \N        [7]  Any character but \n.  Not affected by /s modifier
  \v        [3]  Vertical whitespace
  \V        [3]  Not vertical whitespace
  \h        [3]  Horizontal whitespace
  \H        [3]  Not horizontal whitespace
  \R        [4]  Linebreak
 Sequence   Note    Description
  [...]     [1]  "..." で定義された大かっこ文字クラスのルールに従う文字に
                   マッチング。
                   例: [a-z] は "a", "b", "c", ... "z" にマッチング。
  [[:...:]] [2]  外側の大かっこ文字クラスの内側の POSIX 文字クラスに
                   従う文字にマッチング。
                   例: [[:upper:]] は任意の大文字にマッチング。
  (?[...])  [8]  拡張大かっこ文字クラス
  \w        [3]  "単語" 文字にマッチング (英数字及び "_" に加えて、
                   その他の接続句読点文字と Unicode マークにマッチング)
  \W        [3]  非"単語"文字にマッチング
  \s        [3]  空白文字にマッチング
  \S        [3]  非空白文字にマッチング
  \d        [3]  10 進数字にマッチング
  \D        [3]  非数字にマッチング
  \pP       [3]  名前属性 P にマッチング. 長い名前であれば \p{Prop}
  \PP       [3]  P以外にマッチング
  \X        [4]  Unicode 拡張書記素クラスタ("eXtended grapheme cluster")にマッチング
  \1        [5]  指定した捕捉グループやバッファへの後方参照。
                 '1' には正の整数を指定できます。
  \g1       [5]  指定したまたは前のグループへの後方参照
  \g{-1}    [5]  数値は相対的に前のグループを示す負の値にもできます、また
                 任意で安全にパースするために波かっこで括ることもできます
  \g{name}  [5]  名前指定の後方参照
  \k<name>  [5]  名前指定の後方参照
  \k'name'  [5]  名前指定の後方参照
  \k{name}  [5]  名前指定の後方参照
  \K        [6]  \K の左にある物を保持、$& に含めない
  \N        [7]  \n 以外の任意の文字; /s 修飾子の影響は受けない
  \v        [3]  垂直空白
  \V        [3]  垂直空白以外
  \h        [3]  水平空白
  \H        [3]  水平空白以外
  \R        [4]  行区切り
[1]

詳しくは "Bracketed Character Classes" in perlrecharclass を参照してください。

[2]

詳しくは "POSIX Character Classes" in perlrecharclass を参照してください。

[3]

詳しくは "Unicode Character Properties" in perlunicode を参照してください。

[4]

See "Misc" in perlrebackslash for details.

詳しくは "Misc" in perlrebackslash を参照してください。

[5]

See "Capture groups" below for details.

詳しくは以下の "Capture groups" を参照してください。

[6]

See "Extended Patterns" below for details.

詳しくは以下のSee "Extended Patterns" を参照してください。

[7]

Note that \N has two meanings. When of the form \N{NAME}, it matches the character or character sequence whose name is NAME; and similarly when of the form \N{U+hex}, it matches the character whose Unicode code point is hex. Otherwise it matches any character but \n.

\N には二つの意味があることに注意してください。 \N{NAME} の形式では、これは名前が NAME の文字または文字の並びに マッチングします; 同様に、\N{U+wide hex char} の形式では、Unicode 符号位置が hex の文字にマッチングします。 そうでなければ、\n 以外の任意の文字にマッチングします。

[8]

詳しくは "Extended Bracketed Character Classes" in perlrecharclass を 参照してください。

言明

Besides "^" and "$", Perl defines the following zero-width assertions:

"^""$" の他に、 Perl は以下のゼロ幅の言明を定義しています:

 \b{}   Match at Unicode boundary of specified type
 \B{}   Match where corresponding \b{} doesn't match
 \b     Match a \w\W or \W\w boundary
 \B     Match except at a \w\W or \W\w boundary
 \A     Match only at beginning of string
 \Z     Match only at end of string, or before newline at the end
 \z     Match only at end of string
 \G     Match only at pos() (e.g. at the end-of-match position
        of prior m//g)

A Unicode boundary (\b{}), available starting in v5.22, is a spot between two characters, or before the first character in the string, or after the final character in the string where certain criteria defined by Unicode are met. See "\b{}, \b, \B{}, \B" in perlrebackslash for details.

v5.22 から利用可能である Unicode 境界 (\b{}) は、 Unicode で定義されたある種の基準に一致した、 二つの文字の間か、文字列の最初の文字の前か、 文字列の最後の文字の後の地点です。 詳しくは "\b{}, \b, \B{}, \B" in perlrebackslash を参照してください。

A word boundary (\b) is a spot between two characters that has a \w on one side of it and a \W on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a \W. (Within character classes \b represents backspace rather than a word boundary, just as it normally does in any double-quoted string.) The \A and \Z are just like "^" and "$", except that they won't match multiple times when the /m modifier is used, while "^" and "$" will match at every internal line boundary. To match the actual end of the string and not ignore an optional trailing newline, use \z.

単語境界(\b)は\W にマッチングする文字列の始まりと終わりを 連想するような、片側を \w、もう片側を \W で挟まれている点です。 (文字クラスにおいては \b は単語境界ではなくバックスペースを表します, ちょうどダブルクォート文字列と同じように。) \A 及び \Z"^" 及び "$" と同様ですが、/m 修飾子が 指定されているときに "^" 及び "$" は全ての内部的な行境界に マッチングするのに対して \A 及び \Z は複数回のマッチングには なりません。 文字列の本当の末尾にマッチングさせ、省略可能である末尾の改行を 無視しないようにする \z を使います。

The \G assertion can be used to chain global matches (using m//g), as described in "Regexp Quote-Like Operators" in perlop. It is also useful when writing lex-like scanners, when you have several patterns that you want to match against consequent substrings of your string; see the previous reference. The actual location where \G will match can also be influenced by using pos() as an lvalue: see "pos" in perlfunc. Note that the rule for zero-length matches (see "Repeated Patterns Matching a Zero-length Substring") is modified somewhat, in that contents to the left of \G are not counted when determining the length of the match. Thus the following will not match forever:

\G 言明はグローバルなマッチング(m//g)を連結するために使います; これは "Regexp Quote-Like Operators" in perlop にも説明されています。 これは文字列に対していくつかのパターンを次々にマッチングさせたいといった、 lex 風のスキャナを書きたいときにも便利です; 以前のリファレンスを 参照してください。 \G が実際にマッチングできる位置は pos() を左辺値として 使うことで変更できます: "pos" in perlfunc を参照してください。 ゼロ幅マッチング ("Repeated Patterns Matching a Zero-length Substring" を参照してください) のルールは少し変化することに注意してください、 \G の左にある内容はマッチングの長さを決定するときに 数えられません。 従って次のコードは永遠にマッチングしません:

     my $string = 'ABC';
     pos($string) = 1;
     while ($string =~ /(.\G)/g) {
         print $1;
     }

It will print 'A' and then terminate, as it considers the match to be zero-width, and thus will not match at the same position twice in a row.

これはゼロ幅へのマッチングと見なされ、'A' を出力し終了するので、 行の中で同じ場所に二度はマッチングしません。

It is worth noting that \G improperly used can result in an infinite loop. Take care when using patterns that include \G in an alternation.

適切に使われていない \G は無限ループとなり何の価値もありません。 代替(alternation; |)の中に \G を含んでいるパターンを使う際には 十分注意してください。

Note also that s/// will refuse to overwrite part of a substitution that has already been replaced; so for example this will stop after the first iteration, rather than iterating its way backwards through the string:

s/// は置換部の既に置き換えられた部分を上書きすることを拒否することにも 注意してください; 従って例えばこれは文字列の後ろ向きの反復中ではなく、 最初の反復の後に停止します:

    $_ = "123456789";
    pos = 6;
    s/.(?=.\G)/X/g;
    print;      # prints 1234X6789, not XXXXX6789

捕捉グループ

The grouping construct ( ... ) creates capture groups (also referred to as capture buffers). To refer to the current contents of a group later on, within the same pattern, use \g1 (or \g{1}) for the first, \g2 (or \g{2}) for the second, and so on. This is called a backreference. There is no limit to the number of captured substrings that you may use. Groups are numbered with the leftmost open parenthesis being number 1, etc. If a group did not match, the associated backreference won't match either. (This can happen if the group is optional, or in a different branch of an alternation.) You can omit the "g", and write "\1", etc, but there are some issues with this form, described below.

グループ化構文 ( ... ) は捕捉グループを作成します (そして捕捉バッファとして 参照します)。 同じパターンの中で、あるグループの現在の内容を後で参照するには、 最初のものには \g1 (または \g{1}) を、2 番目には \g2 (または \g{2}) を、以下同様のものを使います。 これを 後方参照 (backreference) と呼びます。 使う捕捉部分文字列の数に制限はありません。 グループはいちばん左の開きかっこを 1 番として番号付けされます。 グループがマッチングしなかった場合、対応する後方参照もマッチングしません。 (これはグループがオプションか、選択の異なる枝の場合に怒ることがあります。) "g" を省略して "\1" などと書くこともできますが、後で述べるように、 この形式にはいくらかの問題があります。

You can also refer to capture groups relatively, by using a negative number, so that \g-1 and \g{-1} both refer to the immediately preceding capture group, and \g-2 and \g{-2} both refer to the group before it. For example:

負数を使うことで捕捉グループを相対的に参照することもできます; \g-1\g{-1} は両方とも直前の捕捉グループを参照し、\g-2\g{-2} は 両方ともその前のグループを参照します。 例えば:

        /
         (Y)            # group 1
         (              # group 2
            (X)         # group 3
            \g{-1}      # backref to group 3
            \g{-3}      # backref to group 1
         )
        /x

would match the same as /(Y) ( (X) \g3 \g1 )/x. This allows you to interpolate regexes into larger regexes and not have to worry about the capture groups being renumbered.

/(Y) ( (X) \g3 \g1 )/x と同じマッチングとなります。 これにより、正規表現をより大きな正規表現に挿入したときに、捕捉グループの 番号を振り直す心配をする必要がなくなります。

You can dispense with numbers altogether and create named capture groups. The notation is (?<name>...) to declare and \g{name} to reference. (To be compatible with .Net regular expressions, \g{name} may also be written as \k{name}, \k<name> or \k'name'.) name must not begin with a number, nor contain hyphens. When different groups within the same pattern have the same name, any reference to that name assumes the leftmost defined group. Named groups count in absolute and relative numbering, and so can also be referred to by those numbers. (It's possible to do things with named capture groups that would otherwise require (??{}).)

数値を全く使わずに、名前付き捕捉グループを作ることが出来ます。 記法は、宣言が (?<name>...)、参照が \g{name} です。 (.Net 正規表現との互換性のために、\g{name}\k{name}, \k<name>, \k'name' とも書けます。) name は数字で始まってはならず、ハイフンを含んではなりません。 同じパターンの中に同じ名前の違うグループがある場合、 この名前での参照は一番左で定義されたものを仮定します。 名前付きグループも絶対や相対番号付けに含まれるので、 番号で参照することも出来ます。 ((??{}) が必要な場合でも名前付き捕捉グループを使うことが出来ます。)

Capture group contents are dynamically scoped and available to you outside the pattern until the end of the enclosing block or until the next successful match in the same scope, whichever comes first. See "Compound Statements" in perlsyn and "Scoping Rules of Regex Variables" in perlvar for more details.

捕捉グループの内容は動的スコープを持ち、パターンの外側でも現在のブロックの 末尾か同じスコープでの次のマッチングの成功のどちらか早いほうまで利用可能です。 さらなる詳細については "Compound Statements" in perlsyn"Scoping Rules of Regex Variables" in perlvar を参照してください。

You can access the contents of a capture group by absolute number (using "$1" instead of "\g1", etc); or by name via the %+ hash, using "$+{name}".

("\g1" などの代わりに "$1" を使って) 絶対値を使うか、 "$+{name}" を使って %+ 経由で名前を使うことで、 捕捉グループの内容にアクセスできます。

Braces are required in referring to named capture groups, but are optional for absolute or relative numbered ones. Braces are safer when creating a regex by concatenating smaller strings. For example if you have qr/$a$b/, and $a contained "\g1", and $b contained "37", you would get /\g137/ which is probably not what you intended.

名前付き捕捉グループを参照するには中かっこが必要です; しかし、絶対数値や相対数値の場合はオプションです。 より小さい文字列を結合して正規表現を作る場合は中かっこを使う方が安全です。 例えば qr/$a$b/$a"\g1" を含み、 $b"37" を含んでいるとき、 結果は /\g137/ となりますが、おそらく望んでいたものではないでしょう。

If you use braces, you may also optionally add any number of blank (space or tab) characters within but adjacent to the braces, like \g{ -1 }, or \k{ name }.

中かっこを使うとき、\g{ -1 }\k{ name } のように、 中かっこの隣の内部に任意の数のブランク (スペースまたはタブ) 文字を追加することもできます。

The \g and \k notations were introduced in Perl 5.10.0. Prior to that there were no named nor relative numbered capture groups. Absolute numbered groups were referred to using \1, \2, etc., and this notation is still accepted (and likely always will be). But it leads to some ambiguities if there are more than 9 capture groups, as \10 could mean either the tenth capture group, or the character whose ordinal in octal is 010 (a backspace in ASCII). Perl resolves this ambiguity by interpreting \10 as a backreference only if at least 10 left parentheses have opened before it. Likewise \11 is a backreference only if at least 11 left parentheses have opened before it. And so on. \1 through \9 are always interpreted as backreferences. There are several examples below that illustrate these perils. You can avoid the ambiguity by always using \g{} or \g if you mean capturing groups; and for octal constants always using \o{}, or for \077 and below, using 3 digits padded with leading zeros, since a leading zero implies an octal constant.

\g\k の記法は Perl 5.10.0 で導入されました。 それより前には名前付きや相対数値指定の捕捉グループはありませんでした。 絶対数値指定のグループは \1, \2 などとして参照でき、この記法はまだ 受け付けられます (そしておそらくいつも受け付けられます)。 しかし、これは 9 を越える捕捉グループがあるとあいまいさがあります; \10 は 10 番目の捕捉グループとも、8 進数で 010 の文字(ASCII で バックスペース)とも解釈できます。 Perl はこのあいまいさを以下のように解決します; \10 の場合、これの前に少なくとも 10 の左かっこがある場合にのみ これを後方参照として解釈します。 同様に、\11 はその前に少なくとも 11 の左かっこがある場合にのみ これを後方参照として解釈します。 以下同様です。 \1 から \9 は常に後方参照として解釈されます。 これを図示するいくつかの例が後にあります。 捕捉グループを意味する場合は常に \g{}\g を使うことで あいまいさを避けられます; そして 8 進定数については常に \o{} を使うか、\077 以下の場合は、 先頭に 0 を付けて 3 桁にします; なぜなら先頭に 0 が付くと 8 進定数を仮定するからです。

The \digit notation also works in certain circumstances outside the pattern. See "Warning on \1 Instead of $1" below for details.

\digit 記法は、ある種の状況ではパターンの外側でも動作します。 詳しくは後述する "Warning on \1 Instead of $1" を参照して下さい。

Examples:

例:

    s/^([^ ]*) *([^ ]*)/$2 $1/;     # swap first two words

    /(.)\g1/                        # find first doubled char
         and print "'$1' is the first doubled character\n";

    /(?<char>.)\k<char>/            # ... a different way
         and print "'$+{char}' is the first doubled character\n";

    /(?'char'.)\g1/                 # ... mix and match
         and print "'$1' is the first doubled character\n";

    if (/Time: (..):(..):(..)/) {   # parse out values
        $hours = $1;
        $minutes = $2;
        $seconds = $3;
    }

    /(.)(.)(.)(.)(.)(.)(.)(.)(.)\g10/   # \g10 is a backreference
    /(.)(.)(.)(.)(.)(.)(.)(.)(.)\10/    # \10 is octal
    /((.)(.)(.)(.)(.)(.)(.)(.)(.))\10/  # \10 is a backreference
    /((.)(.)(.)(.)(.)(.)(.)(.)(.))\010/ # \010 is octal

    $a = '(.)\1';        # Creates problems when concatenated.
    $b = '(.)\g{1}';     # Avoids the problems.
    "aa" =~ /${a}/;      # True
    "aa" =~ /${b}/;      # True
    "aa0" =~ /${a}0/;    # False!
    "aa0" =~ /${b}0/;    # True
    "aa\x08" =~ /${a}0/;  # True!
    "aa\x08" =~ /${b}0/;  # False

Several special variables also refer back to portions of the previous match. $+ returns whatever the last bracket match matched. $& returns the entire matched string. (At one point $0 did also, but now it returns the name of the program.) $` returns everything before the matched string. $' returns everything after the matched string. And $^N contains whatever was matched by the most-recently closed group (submatch). $^N can be used in extended patterns (see below), for example to assign a submatch to a variable.

いくつかの特殊変数もまた以前のマッチングの一部を参照しています。 $+ は最後のマッチングしたブラケットマッチングを返します。 $& はマッチングした文字列全体を返します。 (一頃は $0 もそうでしたが、現在ではこれはプログラム名を返します。) $` はマッチングした文字列の前の全てを返します。 $' はマッチングした文字列の後の全てを返します。 そして $^N には一番最後に閉じたグループ(サブマッチング)に マッチングしたものを含んでいます。 $^N は例えばサブマッチングを変数に格納するため等に拡張パターンの中でも 利用できます(後述)。

These special variables, like the %+ hash and the numbered match variables ($1, $2, $3, etc.) are dynamically scoped until the end of the enclosing block or until the next successful match, whichever comes first. (See "Compound Statements" in perlsyn.)

%+ ハッシュのような特殊変数と、数値によるマッチング変数 ($1, $2, $3 など)はブロックの終端または次のマッチング 成功までのどちらか先に満たした方の、動的なスコープを持ちます。 ("Compound Statements" in perlsyn を参照してください。)

The @{^CAPTURE} array may be used to access ALL of the capture buffers as an array without needing to know how many there are. For instance

@{^CAPTURE} 配列は、いくつあるかを知ることなく、捕捉バッファの 全てに配列としてアクセスするために使えます。 例えば:

    $string=~/$pattern/ and @captured = @{^CAPTURE};

will place a copy of each capture variable, $1, $2 etc, into the @captured array.

これはそれぞれの捕捉変数 $1, $2 などのコピーを @captured 配列に 入れます。

Be aware that when interpolating a subscript of the @{^CAPTURE} array you must use demarcated curly brace notation:

@{^CAPTURE} の添え字を変数展開するときには、 中かっこで境界を定める記法を使わなければならないことに注意してください。

    print "@{^CAPTURE[0]}";

この記法についての詳細は "Demarcated variable names using braces" in perldata を参照してください。

NOTE: Failed matches in Perl do not reset the match variables, which makes it easier to write code that tests for a series of more specific cases and remembers the best match.

補足: Perl において失敗したマッチングはマッチング変数をリセットしません; これはより特殊化させる一連のテストを書くことや、 最善のマッチングを書くことを容易にします。

WARNING: If your code is to run on Perl 5.16 or earlier, beware that once Perl sees that you need one of $&, $`, or $' anywhere in the program, it has to provide them for every pattern match. This may substantially slow your program.

警告: あなたのコードが Perl 5.16 以前で実行されるものの場合、 Perl は、一旦プログラム中のどこかで $&, $`, $' の いずれかを必要としていることを見つけると、全てのパターンマッチングで それらを提供しなければなあらないことに注意してください。 これはあなたのプログラムを大幅に遅くさせるでしょう。

Perl uses the same mechanism to produce $1, $2, etc, so you also pay a price for each pattern that contains capturing parentheses. (To avoid this cost while retaining the grouping behaviour, use the extended regular expression (?: ... ) instead.) But if you never use $&, $` or $', then patterns without capturing parentheses will not be penalized. So avoid $&, $', and $` if you can, but if you can't (and some algorithms really appreciate them), once you've used them once, use them at will, because you've already paid the price.

Perl は $1, $2 等の生成にも同じメカニズムを使っているので、 キャプチャのかっこに含まれるそれぞれのパターンにも 同じ料金を払っています。 (グループ化の振る舞いを維持しつつこのコストを削減するには 拡張正規表現 (?: ... ) を代わりに使います (訳注:Perl拡張というだけで /x 修飾子は不要)。) ですが $&, $` または $' を一度も使わなければ、 キャプチャのかっこをもたないパターンではこの不利益はなくなります。 この為、可能であれば $&, $', 及び $` を削除しましょう: しかしそれができなかった(そしてそれらを 本当に理解しているアルゴリズムがあるのであれば)、一旦 それらを使った時点でそれ以降は自由にそれらを使うことができます; なぜならあなたは(一度使った時点で)既に代価を払っているので。

Perl 5.16 introduced a slightly more efficient mechanism that notes separately whether each of $`, $&, and $' have been seen, and thus may only need to copy part of the string. Perl 5.20 introduced a much more efficient copy-on-write mechanism which eliminates any slowdown.

Perl 5.16 では、$`, $&, $' のそれぞれが現れるかどうかを 個別に記録するという少し効率的な機構が導入され、 従って文字列の一部分だけコピーするようになりました。 Perl 5.20 では、全く遅くならない遙かに効率的なコピーオンライト機構を 導入しました。

As another workaround for this problem, Perl 5.10.0 introduced ${^PREMATCH}, ${^MATCH} and ${^POSTMATCH}, which are equivalent to $`, $& and $', except that they are only guaranteed to be defined after a successful match that was executed with the /p (preserve) modifier. The use of these variables incurs no global performance penalty, unlike their punctuation character equivalents, however at the trade-off that you have to tell perl when you want to use them. As of Perl 5.20, these three variables are equivalent to $`, $& and $', and /p is ignored.

この問題に対するもう一つの解決策として、Perl 5.10.0 からは $`, $&, $' と 等価だけれども /p (preseve) 修飾子を伴って実行されたマッチングが 成功した後でのみ定義されることが保証される ${^PREMATCH}${^MATCH} 及び ${^POSTMATCH} を導入しました。 これらの変数の使用は利用したいときに perl に伝える必要がある代わりに、 等価な記号変数とは違い全体的なパフォーマンスの低下を引き起こしません。 Perl 5.20 からこれら三つの変数は $`, $&, $' と等価となり、 /p は無視されます。

メタ文字のクォート

Backslashed metacharacters in Perl are alphanumeric, such as \b, \w, \n. Unlike some other regular expression languages, there are no backslashed symbols that aren't alphanumeric. So anything that looks like \\, \(, \), \[, \], \{, or \} is always interpreted as a literal character, not a metacharacter. This was once used in a common idiom to disable or quote the special meanings of regular expression metacharacters in a string that you want to use for a pattern. Simply quote all non-"word" characters:

Perl において逆スラッシュで表現されるメタ文字は \b, \w, \n のように英数字です。 他の正規表現言語とは異なり、英数字でない逆スラッシュ付きシンボルは ありません。 なので \\, \(, \), \[, \], \{, or \} といったものは 全てメタ文字ではなくリテラル文字です。 これはパターンで使いたい文字列の中で正規表現のメタ文字としての特殊な意味を 無効化またはクォートするための一般的な指標として使われてきました。 「単語」でない全ての文字は単にクォートします:

    $pattern =~ s/(\W)/\\$1/g;

(If use locale is set, then this depends on the current locale.) Today it is more common to use the quotemeta() function or the \Q metaquoting escape sequence to disable all metacharacters' special meanings like this:

(もし use locale が有効であれば、これは現在のロケールに依存します。) 今日では特殊な意味を持つメタ文字を全て無効にするためには次のように quotemeta() 関数か \Q メタクォート エスケープシーケンスを使うのがより一般的です:

    /$unquoted\Q$quoted\E$unquoted/

Beware that if you put literal backslashes (those not inside interpolated variables) between \Q and \E, double-quotish backslash interpolation may lead to confusing results. If you need to use literal backslashes within \Q...\E, consult "Gory details of parsing quoted constructs" in perlop.

\Q 及び \E の間でリテラルとして逆スラッシュをおくとき (埋め込んだ変数の中でではない)には、二重にクォートした逆スラッシュの 埋め込みは困惑した結果となるでしょう。 もし \Q...\E でリテラルとしての逆スラッシュを使う 必要がある のなら、 "Gory details of parsing quoted constructs" in perlop を参照してください。

quotemeta() and \Q are fully described in "quotemeta" in perlfunc.

quotemeta()\Q"quotemeta" in perlfunc に完全に記述されています。

拡張パターン

Perl also defines a consistent extension syntax for features not found in standard tools like awk and lex. The syntax for most of these is a pair of parentheses with a question mark as the first thing within the parentheses. The character after the question mark indicates the extension.

Perl は awklex といった標準的なツールでは見られない機能のための 拡張構文も定義しています。 これらのほとんどの構文は対のかっことかっこ内の最初に疑問符の形をとります。 疑問符の後の文字で拡張を区別します。

A question mark was chosen for this and for the minimal-matching construct because 1) question marks are rare in older regular expressions, and 2) whenever you see one, you should stop and "question" exactly what is going on. That's psychology....

疑問符は 1) それが古い正規表現で使われることは稀であること、そして 2) それを見かけると何が行われるのか本当に「疑問に」思って止まることから、 これのためと最小マッチング構成子のために選ばれました。 これが心理学です…。

(?#text)

A comment. The text is ignored. Note that Perl closes the comment as soon as it sees a ")", so there is no way to put a literal ")" in the comment. The pattern's closing delimiter must be escaped by a backslash if it appears in the comment.

コメント。 text は無視されます。 Perl は ")" を見つけると直ぐにコメントを閉じる点に注意してください; この為リテラル ")" をコメント中におくことはできません。 パターンの閉じ区切り文字がコメントに見えるようなものなら、 逆スラッシュでエスケープしなければなりません。

See "/x" for another way to have comments in patterns.

パターンの中にコメントを入れるもう一つの方法については "/x" を参照してください。

Note that a comment can go just about anywhere, except in the middle of an escape sequence. Examples:

コメントは、エスケープシーケンスの途中を除いて、 どこにでも入れることができることに注意してください。 例:

 qr/foo(?#comment)bar/'  # Matches 'foobar'

 # The pattern below matches 'abcd', 'abccd', or 'abcccd'
 qr/abc(?#comment between literal and its quantifier){1,3}d/

 # The pattern below generates a syntax error, because the '\p' must
 # be followed immediately by a '{'.
 qr/\p(?#comment between \p and its property name){Any}/

 # The pattern below generates a syntax error, because the initial
 # '\(' is a literal opening parenthesis, and so there is nothing
 # for the  closing ')' to match
 qr/\(?#the backslash means this isn't a comment)p{Any}/

 # Comments can be used to fold long patterns into multiple lines
 qr/First part of a long regex(?#
   )remaining part/
(?adlupimnsx-imnsx)
(?^alupimnsx)

Zero or more embedded pattern-match modifiers, to be turned on (or turned off if preceded by "-") for the remainder of the pattern or the remainder of the enclosing pattern group (if any).

ゼロ以上のパターンマッチング修飾子; パターンの残りまたは(もしあれば)包含しているパターングループの残りで 有効にする(または "-" が前置されていれば解除する)。

This is particularly useful for dynamically-generated patterns, such as those read in from a configuration file, taken from an argument, or specified in a table somewhere. Consider the case where some patterns want to be case-sensitive and some do not: The case-insensitive ones merely need to include (?i) at the front of the pattern. For example:

これは設定ファイルから読む、引数から取る、どこかのテーブルで 指定されている箇所から動的生成されたパターンを使うときに特に便利です。 パターンの一部では大文字小文字を区別したいけれども別の箇所では 区別しないといったケースを考えてみます: 区別をしない場所では 単にパターンの先頭に (?i) を含めるだけです。 例えば:

    $pattern = "foobar";
    if ( /$pattern/i ) { }

    # more flexible:

    $pattern = "(?i)foobar";
    if ( /$pattern/ ) { }

These modifiers are restored at the end of the enclosing group. For example,

これらの修飾子は包含しているグループの最後で復元(restore)されます。 例えば、

    ( (?i) blah ) \s+ \g1

will match blah in any case, some spaces, and an exact (including the case!) repetition of the previous word, assuming the /x modifier, and no /i modifier outside this group.

blah に大文字小文字の区別なくマッチングし、 いくつかの空白、そして前の単語その物(大文字小文字の区別まで含めて!)に 再度マッチングします; ここではこのグループの外側で /x 修飾子を持ち、 /i 修飾子を持たないものとします。

These modifiers do not carry over into named subpatterns called in the enclosing group. In other words, a pattern such as ((?i)(?&NAME)) does not change the case-sensitivity of the NAME pattern.

これらの修飾子は囲まれたグループで呼び出された名前付き部分パターンには 持ち越されません。 言い換えると、((?i)(?&NAME)) のようなパターンは、 NAME パターンが大文字小文字を認識するのを変更しません。

A modifier is overridden by later occurrences of this construct in the same scope containing the same modifier, so that

修飾子は、同じスコープ内で同じ修飾子を含む この構文が後に出現すると上書きされるので:

    /((?im)foo(?-m)bar)/

matches all of foobar case insensitively, but uses /m rules for only the foo portion. The "a" flag overrides aa as well; likewise aa overrides "a". The same goes for "x" and xx. Hence, in

は、foobar のすべてに大文字小文字を区別せずにマッチングしますが、 foo 部分のみに /m の規則を使います。 "a" フラグは aa も上書きします; 同様に、aa"a"を上書きします。 同じことが "x"xx についても当てはまります。 したがって:

    /(?-x)foo/xx

both /x and /xx are turned off during matching foo. And in

/x/xx は両方とも、foo のマッチング中はオフになります。 そして:

    /(?x)foo/x

/x but NOT /xx is turned on for matching foo. (One might mistakenly think that since the inner (?x) is already in the scope of /x, that the result would effectively be the sum of them, yielding /xx. It doesn't work that way.) Similarly, doing something like (?xx-x)foo turns off all "x" behavior for matching foo, it is not that you subtract 1 "x" from 2 to get 1 "x" remaining.

foo にマッチングする間、/xx ではなく /x がオンになります。 (内部 (?x) はすでに /x の範囲内にあるので、結果は実質的に それらの和になり、/xx が生成されると誤って考えるかもしれません。 そうはなりません。) 同様に、(?xx-x)foo のようなことをすると、foo とマッチングする間 "x" の動作がすべてオフになります; 二つの "x" から一つ引いて一つの "x" が残るということにはなりません。

Any of these modifiers can be set to apply globally to all regular expressions compiled within the scope of a use re. See "'/flags' mode" in re.

それらの変更のどれもセットでき、use reのスコープ内でグローバルに 全てのコンパイルされた正規表現に適用されます。"'/flags' mode" in re を見てください。

Starting in Perl 5.14, a "^" (caret or circumflex accent) immediately after the "?" is a shorthand equivalent to d-imnsx. Flags (except "d") may follow the caret to override it. But a minus sign is not legal with it.

Perl 5.14から、"^"(キャレットか曲折アクセント)が"?"のすぐ 後ろにつくと、d-imnsx と同じになります。フラグ("d"以外の) をキャレットに続けることで、上書きできます。 ですが、マイナス記号は一緒に使えません。

Note that the "a", "d", "l", "p", and "u" modifiers are special in that they can only be enabled, not disabled, and the "a", "d", "l", and "u" modifiers are mutually exclusive: specifying one de-specifies the others, and a maximum of one (or two "a"'s) may appear in the construct. Thus, for example, (?-p) will warn when compiled under use warnings; (?-d:...) and (?dl:...) are fatal errors.

"a", "d", "l", "p", "u" 修飾子は有効にできるのみで、 無効にはできない点、 そして "a", "d", "l", "u" 修飾子は 互いに排他であるという点で特別です: 一つを指定すると他のものの指定を解除し、構文中に最大で一つ (または二つの "a") だけが現れます。 従って 例えば (?-p)use warnings の下でコンパイルされると 警告を発します; (?-d:...)(?dl:...) は致命的エラーです。

Note also that the "p" modifier is special in that its presence anywhere in a pattern has a global effect.

パターン中のどこにあってもグローバルな影響があるという意味で "p" 修飾子が特別であることにも注意してください。

Having zero modifiers makes this a no-op (so why did you specify it, unless it's generated code), and starting in v5.30, warns under use re 'strict'.

修飾子がない場合、これは何もせず (なので、生成されたコードでない場合、 なぜこれを指定したのでしょう?)、v5.30 から、 use re 'strict' の警告が出ます。

(?:pattern)
(?adluimnsx-imnsx:pattern)
(?^aluimnsx:pattern)

This is for clustering, not capturing; it groups subexpressions like "()", but doesn't make backreferences as "()" does. So

これはキャプチャではなくクラスタです; これは "()" のように部分式を グループ化しますが "()" が行うような後方参照は行いません。 つまり、

    @fields = split(/\b(?:a|b|c)\b/)

matches the same field delimiters as

次と同じフィールド区切り文字にマッチングしますが:

    @fields = split(/\b(a|b|c)\b/)

but doesn't spit out the delimiters themselves as extra fields (even though that's the behaviour of "split" in perlfunc when its pattern contains capturing groups). It's also cheaper not to capture characters if you don't need to.

(例えそれが捕捉グループを含むときの "split" in perlfunc の振る舞いで あったとしても) 区切り文字自身を余計なフィールドとして引き出しません。 また不要であれば文字のキャプチャを行わないため低コストです。

Any letters between "?" and ":" act as flags modifiers as with (?adluimnsx-imnsx). For example,

"?" 及び ":" の間の文字は (?adluimnsx-imnsx) のような フラグ修飾子として動作します。 例えば、

    /(?s-i:more.*than).*million/i

is equivalent to the more verbose

はより冗長に書けば以下と等価です

    /(?:(?s-i)more.*than).*million/i

Note that any () constructs enclosed within this one will still capture unless the /n modifier is in effect.

これの中の () 構文は、/n が有効でない限りまだ捕捉することに 注意してください。

Like the "(?adlupimnsx-imnsx)" construct, aa and "a" override each other, as do xx and "x". They are not additive. So, doing something like (?xx-x:foo) turns off all "x" behavior for matching foo.

"(?adlupimnsx-imnsx)" 構文と同様、xx"x"と同様に、aa"a" は互いに上書きします。 これらは加法的ではありません。 したがって、(?xx-x:foo) のようなことを行うと、 foo にマッチングする間、"x" の動作がすべてオフになります。

Starting in Perl 5.14, a "^" (caret or circumflex accent) immediately after the "?" is a shorthand equivalent to d-imnsx. Any positive flags (except "d") may follow the caret, so

Perl 5.14 から、"^"(キャレットあるいは曲折アクセント)が "?" のすぐ 後ろにつくと、d-imnsx と同じになります。 どのような肯定のフラグ("d" 以外の)もキャレットに続けることができます; そのため、

    (?^x:foo)

is equivalent to

は、以下と同じになります。

    (?x-imns:foo)

The caret tells Perl that this cluster doesn't inherit the flags of any surrounding pattern, but uses the system defaults (d-imnsx), modified by any flags specified.

キャレットは、Perlにこのクラスターはパターンの周りのどのフラグも 引き継がずに、代わりに、システムのデフォルトのフラグ (d-imnsx) を使うことを教えます; 指定されている他のフラグによって変更されます。

The caret allows for simpler stringification of compiled regular expressions. These look like

キャレットはより簡単なコンパイルされた正規表現の文字列化をすることが できます。次のものは

    (?^:pattern)

with any non-default flags appearing between the caret and the colon. A test that looks at such stringification thus doesn't need to have the system default flags hard-coded in it, just the caret. If new flags are added to Perl, the meaning of the caret's expansion will change to include the default for those flags, so the test will still work, unchanged.

キャレットとコロンの間には、デフォルトでないフラグがありません。 このような文字列化を見るテストには、したがって、システムのデフォルトのフラグを その中にハードコードする必要はなく、ただキャレットを使います。新しいフラグが Perlに追加されたら、キャレットを展開した意味はそれらのフラグのためのデフォルトを 含むように変更されます; そのために、このテストは、それでも何も変えずに 動くでしょう。

Specifying a negative flag after the caret is an error, as the flag is redundant.

キャレットの後ろに否定のフラグを付けると、余計なフラグであるとして、 エラーになります。

Mnemonic for (?^...): A fresh beginning since the usual use of a caret is to match at the beginning.

(?^...)の覚え方: 新鮮な開始; 通常のキャレットの使い方は文字列の開始の マッチなので。

(?|pattern)

This is the "branch reset" pattern, which has the special property that the capture groups are numbered from the same starting point in each alternation branch. It is available starting from perl 5.10.0.

これは各代替分岐において捕捉グループを同じ番号から始める特殊な 属性を持っている、「ブランチリセット(branch reset)」パターンです。 これは perl 5.10.0 から提供されています。

Capture groups are numbered from left to right, but inside this construct the numbering is restarted for each branch.

捕捉グループは左から右へと番号が振られますが、この構成子の内側では 各分岐毎に番号はリセットされます。

The numbering within each branch will be as normal, and any groups following this construct will be numbered as though the construct contained only one branch, that being the one with the most capture groups in it.

各分岐内での番号付けは通常通りに行われ、この構成子の後に続くグループは その中で捕捉グループが一番多かった分岐のみが 格納されていたかのように番号付けされていきます。

This construct is useful when you want to capture one of a number of alternative matches.

この構成子はいくつかの代替マッチングの1つを捕捉したいときに便利です。

Consider the following pattern. The numbers underneath show in which group the captured content will be stored.

以下のパターンを想像してみてください。 下側の番号は内容の格納されるグループを示します。

    # before  ---------------branch-reset----------- after
    / ( a )  (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x
    # 1            2         2  3        2     3     4

Be careful when using the branch reset pattern in combination with named captures. Named captures are implemented as being aliases to numbered groups holding the captures, and that interferes with the implementation of the branch reset pattern. If you are using named captures in a branch reset pattern, it's best to use the same names, in the same order, in each of the alternations:

名前付き捕捉と枝リセットパターンを組み合わせて使うときには注意してください。 名前付き捕捉は捕捉を保持している番号付きグループへの別名として 実装されていて、枝リセットパターンの実装を妨害します。 枝リセットパターンで名前付き捕捉を使うときは、それぞれの代替で 同じ名前を同じ順番で使うのが最良です:

   /(?|  (?<a> x ) (?<b> y )
      |  (?<a> z ) (?<b> w )) /x

Not doing so may lead to surprises:

そうしないと驚くことになります:

  "12" =~ /(?| (?<a> \d+ ) | (?<b> \D+))/x;
  say $+{a};    # Prints '12'
  say $+{b};    # *Also* prints '12'.

The problem here is that both the group named a and the group named b are aliases for the group belonging to $1.

ここでの問題は、a という名前のグループと b という名前の が両方ともグループ $1 への別名であることです。

Lookaround Assertions

Lookaround assertions are zero-width patterns which match a specific pattern without including it in $&. Positive assertions match when their subpattern matches, negative assertions match when their subpattern fails. Lookbehind matches text up to the current match position, lookahead matches text following the current match position.

先読み及び後読みの言明(assertion)は $& の中に 含めない特定のパターンにマッチングするゼロ幅のパターンです。 正の言明はその部分パターンがマッチングしたときにマッチングし、 負の言明はその部分パターンが失敗したときにマッチングします。 後読みのマッチングは今のマッチング位置までのテキストにマッチングし、 先読みの言明は今のマッチング位置の先にあるテキストにマッチングします。

(?=pattern)
(*pla:pattern)
(*positive_lookahead:pattern)

A zero-width positive lookahead assertion. For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab in $&.

ゼロ幅の正の先読み言明。 例えば、/\w+(?=\t)/ はタブが続く単語にマッチングしますが、タブは $& に含まれません。

(?!pattern)
(*nla:pattern)
(*negative_lookahead:pattern)

A zero-width negative lookahead assertion. For example /foo(?!bar)/ matches any occurrence of "foo" that isn't followed by "bar". Note however that lookahead and lookbehind are NOT the same thing. You cannot use this for lookbehind.

ゼロ幅の負の先読み言明。 例えば /foo(?!bar)/ は "bar" が続かない全ての "foo" にマッチングします。 しかしながら先読みと後読みは同じ物では ない点に注意してください。 これを後読みに使うことはできません。

If you are looking for a "bar" that isn't preceded by a "foo", /(?!foo)bar/ will not do what you want. That's because the (?!foo) is just saying that the next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" will match. Use lookbehind instead (see below).

もし "foo" が前にない "bar" を探しているのなら、 /(?!foo)bar/ では欲しい物にはなりません。 なぜなら (?!foo) は次のものが "foo" ではないとだけいっているのです -- そしてそうではなく、そこには "bar" があるので、"foobar" はマッチングします。 (後述の) 後方参照を使ってください。

(?<=pattern)
\K
(*plb:pattern)
(*positive_lookbehind:pattern)

A zero-width positive lookbehind assertion. For example, /(?<=\t)\w+/ matches a word that follows a tab, without including the tab in $&.

ゼロ幅の正の後読みの言明。 例えば、/(?<=\t)\w+/ は タブに続く単語にマッチングしますが、タブは $& に 含まれません。

Prior to Perl 5.30, it worked only for fixed-width lookbehind, but starting in that release, it can handle variable lengths from 1 to 255 characters as an experimental feature. The feature is enabled automatically if you use a variable length positive lookbehind assertion.

Perl 5.30 より前では、固定幅の後読みのみが動作しますが、このリリースからは、 実験的な機能として 1 から 255 文字の可変長を処理できます。 可変長の正の後読みの言明を使用すると、この機能は自動的に有効になります。

In Perl 5.35.10 the scope of the experimental nature of this construct has been reduced, and experimental warnings will only be produced when the construct contains capturing parenthesis. The warnings will be raised at pattern compilation time, unless turned off, in the experimental::vlb category. This is to warn you that the exact contents of capturing buffers in a variable length positive lookbehind is not well defined and is subject to change in a future release of perl.

Perl 5.35.10 から、この構文の実験性は縮小され、実験的警告は この構文が捕捉かっこを含んでいる場合にのみ出力されます。 experimental::vlb カテゴリでオフにしない限り、パターンのコンパイル時に 警告が表示されます。 これは、可変長の正の後読みでの捕捉バッファの正確な内容はよく 定義されておらず、将来のリリースの perl で変更されるかもしれないことを 警告するものです。

Currently if you use capture buffers inside of a positive variable length lookbehind the result will be the longest and thus leftmost match possible. This means that

現在の所、正の可変長後読みの内部で捕捉バッファを使うと、 結果は最長で、従って可能な一番左側のマッチングになります。 つまり:

    "aax" =~ /(?=x)(?<=(a|aa))/
    "aax" =~ /(?=x)(?<=(aa|a))/
    "aax" =~ /(?=x)(?<=(a{1,2}?)/
    "aax" =~ /(?=x)(?<=(a{1,2})/

will all result in $1 containing "aa". It is possible in a future release of perl we will change this behavior.

これらは全て $1"aa" が入ることになります。 将来のリリースの perl でこの振る舞いは変わる可能性があります。

There is a special form of this construct, called \K (available since Perl 5.10.0), which causes the regex engine to "keep" everything it had matched prior to the \K and not include it in $&. This effectively provides non-experimental variable-length lookbehind of any length.

(Perl 5.10.0 から利用可能な) \K というこの構成子の特殊な形式もあります; これは正規表現エンジンに対してそれが \K までにマッチングした すべてのものを"取っておいて"、$& には含めないようにさせます。 これは事実上実験的でない任意の長さの可変長の後読みを提供します。

And, there is a technique that can be used to handle variable length lookbehinds on earlier releases, and longer than 255 characters. It is described in http://www.drregex.com/2019/02/variable-length-lookbehinds-actually.html.

そして、以前のリリースや、255 文字より長い可変長後ろ読みを扱うのに使える テクニックがあります。 これは http://www.drregex.com/2019/02/variable-length-lookbehinds-actually.html に 記述されています。

Note that under /i, a few single characters match two or three other characters. This makes them variable length, and the 255 length applies to the maximum number of characters in the match. For example qr/\N{LATIN SMALL LETTER SHARP S}/i matches the sequence "ss". Your lookbehind assertion could contain 127 Sharp S characters under /i, but adding a 128th would generate a compilation error, as that could match 256 "s" characters in a row.

/i の下では、いくつかの単一の文字が 2 または 3 の他の文字に マッチングすることに注意してください。 これは後読みを可変長にし、長さ 255 はマッチングの中の文字の最大数に 適用されます。 例えば、qr/\N{LATIN SMALL LETTER SHARP S}/i は並び "ss" に マッチングします。 あなたの後読み言明は /i の下で 127 個の Sharp S 文字を含むことは できますが、128 個目を追加するとコンパイルエラーが生成されます; これは 256 個連続した "s" 文字にマッチングすることがあるからです。

The use of \K inside of another lookaround assertion is allowed, but the behaviour is currently not well defined.

他の先読み及び後読みの言明の中での利用も可能ですが、その振る舞いは 今のところあまり定義されていません。

For various reasons \K may be significantly more efficient than the equivalent (?<=...) construct, and it is especially useful in situations where you want to efficiently remove something following something else in a string. For instance

いくつかの理由から、\K は等価な (?<=...) 構成子より非常に効率的で、文字列の中で何かに続いている何かを効率的に 取り除きたいようなシチュエーションで効果的に役立ちます。 例えば

  s/(foo)bar/$1/g;

can be rewritten as the much more efficient

次のようにより効率的に書き直せます

  s/foo\Kbar//g;

Use of the non-greedy modifier "?" may not give you the expected results if it is within a capturing group within the construct.

非貪欲修飾子 "?" の使用は、この構文の中の捕捉グループの中では 想定される結果にならないかもしれません。

(?<!pattern)
(*nlb:pattern)
(*negative_lookbehind:pattern)

A zero-width negative lookbehind assertion. For example /(?<!bar)foo/ matches any occurrence of "foo" that does not follow "bar".

ゼロ幅の負の後読みの言明。 例えば /(?<!bar)foo/ は "bar" に続いていない任意の "foo" に マッチングします。

Prior to Perl 5.30, it worked only for fixed-width lookbehind, but starting in that release, it can handle variable lengths from 1 to 255 characters as an experimental feature. The feature is enabled automatically if you use a variable length negative lookbehind assertion.

Perl 5.30 より前では、固定幅の後読みのみが動作しますが、このリリースからは、 実験的な機能として 1 から 255 文字の可変長を処理できます。 可変長の負の後読みの言明を使用すると、この機能は自動的に有効になります。

In Perl 5.35.10 the scope of the experimental nature of this construct has been reduced, and experimental warnings will only be produced when the construct contains capturing parentheses. The warnings will be raised at pattern compilation time, unless turned off, in the experimental::vlb category. This is to warn you that the exact contents of capturing buffers in a variable length negative lookbehind is not well defined and is subject to change in a future release of perl.

Perl 5.35.10 から、この構文の実験性は縮小され、実験的警告は この構文が捕捉かっこを含んでいる場合にのみ出力されます。 experimental::vlb カテゴリでオフにしない限り、パターンのコンパイル時に 警告が表示されます。 これは、可変長の負の後読みでの捕捉バッファの正確な内容はよく 定義されておらず、将来のリリースの perl で変更されるかもしれないことを 警告するものです。

Currently if you use capture buffers inside of a negative variable length lookbehind the result may not be what you expect, for instance:

現在のところ、負の可変長後読みの内部で捕捉バッファを使うと、 結果は想定したものではないかもしれません; 例えば:

    say "axfoo"=~/(?=foo)(?<!(a|ax)(?{ say $1 }))/ ? "y" : "n";

will output the following:

これは次のものを出力します:

    a
    no

which does not make sense as this should print out "ax" as the "a" does not line up at the correct place. Another example would be:

これはつじつまが合っていません; "a" が正しい位置にないので "ax" が 出力されるべきだからです。 もう一つの例としては:

    say "yes: '$1-$2'" if "aayfoo"=~/(?=foo)(?<!(a|aa)(a|aa)x)/;

will output the following:

これは次のものを出力します:

    yes: 'aa-a'

It is possible in a future release of perl we will change this behavior so both of these examples produced more reasonable output.

これらの例の両方がより妥当な出力をするように 将来のリリースの perl でこの振る舞いを変える可能性があります。

Note that we are confident that the construct will match and reject patterns appropriately, the undefined behavior strictly relates to the value of the capture buffer during or after matching.

この構文がパターンを適切にマッチングまたは拒否していることには 自信があるので、未定義の振る舞いは厳密にマッチング中またはその後の 捕捉バッファの値に関連するもののみであるということに注意してください。

There is a technique that can be used to handle variable length lookbehind on earlier releases, and longer than 255 characters. It is described in http://www.drregex.com/2019/02/variable-length-lookbehinds-actually.html.

以前のリリースや、255 文字より長い可変長後ろ読みを扱うのに使える テクニックがあります。 これは http://www.drregex.com/2019/02/variable-length-lookbehinds-actually.html に 記述されています。

Note that under /i, a few single characters match two or three other characters. This makes them variable length, and the 255 length applies to the maximum number of characters in the match. For example qr/\N{LATIN SMALL LETTER SHARP S}/i matches the sequence "ss". Your lookbehind assertion could contain 127 Sharp S characters under /i, but adding a 128th would generate a compilation error, as that could match 256 "s" characters in a row.

/i の下では、いくつかの単一の文字が 2 または 3 の他の文字に マッチングすることに注意してください。 これは後読みを可変長にし、長さ 255 はマッチングの中の文字の最大数に 適用されます。 例えば、qr/\N{LATIN SMALL LETTER SHARP S}/i は並び "ss" に マッチングします。 あなたの後読み言明は /i の下で 127 個の Sharp S 文字を含むことは できますが、128 個目を追加するとコンパイルエラーが生成されます; これは 256 個連続した "s" 文字にマッチングすることがあるからです。

Use of the non-greedy modifier "?" may not give you the expected results if it is within a capturing group within the construct.

非貪欲修飾子 "?" の使用は、この構文の中の捕捉グループの中では 想定される結果にならないかもしれません。

(?<NAME>pattern)
(?'NAME'pattern)

A named capture group. Identical in every respect to normal capturing parentheses () but for the additional fact that the group can be referred to by name in various regular expression constructs (like \g{NAME}) and can be accessed by name after a successful match via %+ or %-. See perlvar for more details on the %+ and %- hashes.

名前付の捕捉グループ。 通常のキャプチャかっこ () と同様ですがそれに加えて、 グループは(\g{NAME} のように) 様々な正規表現構文で名前で参照でき、 マッチングに成功したあと %+%- を使って名前によって アクセスできます。 %+ 及び %- ハッシュに関する詳細は perlvar を 参照してください。

If multiple distinct capture groups have the same name, then $+{NAME} will refer to the leftmost defined group in the match.

複数の異なる捕捉グループが同じ名前を持っていたときには $+{NAME} はマッチングの中で一番左で定義されたグループを参照します。

The forms (?'NAME'pattern) and (?<NAME>pattern) are equivalent.

二つの形式 (?'NAME'pattern)(?<NAME>pattern) は 等価です。

NOTE: While the notation of this construct is the same as the similar function in .NET regexes, the behavior is not. In Perl the groups are numbered sequentially regardless of being named or not. Thus in the pattern

補足: これを構成する記法は 類似していている .NET での正規表現と 同じですが、振る舞いは異なります。 Perl ではグループは名前がついているかどうかにかかわらず順番に番号が 振られます。 従って次のパターンにおいて

  /(x)(?<foo>y)(z)/

$+{foo} will be the same as $2, and $3 will contain 'z' instead of the opposite which is what a .NET regex hacker might expect.

$+{foo}$2 と同じであり、$3 には .NET 正規表現に 慣れた人が予測するのとは異なり 'z' が含まれます。

Currently NAME is restricted to simple identifiers only. In other words, it must match /^[_A-Za-z][_A-Za-z0-9]*\z/ or its Unicode extension (see utf8), though it isn't extended by the locale (see perllocale).

現在のところ NAME はシンプルな識別子のみに制限されています。 言い換えると、/^[_A-Za-z][_A-Za-z0-9]*\z/ または その Unicode 拡張にマッチングしなければなりません (utf8 も参照); しかしロケールでは拡張されません (perllocale 参照)。

NOTE: In order to make things easier for programmers with experience with the Python or PCRE regex engines, the pattern (?P<NAME>pattern) may be used instead of (?<NAME>pattern); however this form does not support the use of single quotes as a delimiter for the name.

補足: Python や PCRE 正規表現エンジンになれたプログラマが 楽になるように、(?<NAME>pattern) の代わりに (?P<NAME>pattern) のパターンを使うことも できます; しかしこの形式は名前のデリミタとして シングルクォートの使用はサポートされていません。

\k<NAME>
\k'NAME'
\k{NAME}

Named backreference. Similar to numeric backreferences, except that the group is designated by name and not number. If multiple groups have the same name then it refers to the leftmost defined group in the current match.

名前による後方参照。 数値によってではなく名前によってグループを指定する点を除いて、名前による 後方参照と似ています。 もし同じ名前の複数のグループがあったときには現在のマッチングで 一番左に定義されているグループを参照します。

It is an error to refer to a name not defined by a (?<NAME>) earlier in the pattern.

パターン内で (?<NAME>) によって定義されていない名前を 参照するとエラーになります。

All three forms are equivalent, although with \k{ NAME }, you may optionally have blanks within but adjacent to the braces, as shown.

三つの形式はどれも等価ですが、 \k{ NAME } では、前述の通り、 中かっこの隣の内部に空白を使うことができます。

NOTE: In order to make things easier for programmers with experience with the Python or PCRE regex engines, the pattern (?P=NAME) may be used instead of \k<NAME>.

補足: Python や PCRE 正規表現エンジンになれたプログラマが楽に なるように、\k<NAME> の代わりに (?P=NAME) のパターンを使うこともできます。

(?{ code })

WARNING: Using this feature safely requires that you understand its limitations. Code executed that has side effects may not perform identically from version to version due to the effect of future optimisations in the regex engine. For more information on this, see "Embedded Code Execution Frequency".

警告: この機能を安全に使うには、その制限について理解することが必要です。 副作用を持つコードの実行は今後の正規表現エンジンの最適化の影響で バージョン間で必ずしも同じになるとは限らないでしょう。 これに関するさらなる情報については、"Embedded Code Execution Frequency" を 参照してください。

This zero-width assertion executes any embedded Perl code. It always succeeds, and its return value is set as $^R.

このゼロ幅の言明は埋め込まれた任意の Perl コードを実行します。 これは常に(正規表現として)成功し、返り値は $^R に設定されます。

In literal patterns, the code is parsed at the same time as the surrounding code. While within the pattern, control is passed temporarily back to the perl parser, until the logically-balancing closing brace is encountered. This is similar to the way that an array index expression in a literal string is handled, for example

リテラルなパターンでは、このコードは周りのコードと同時にパースされます。 このパターンの中では、 論理的にバランスが取れる閉じかっこが現れるまで、 制御文字は一時的に perl パーサーに渡されます。 これはリテラル文字列の中の配列添字表現の扱われ方と似ています; 例えば:

    "abc$array[ 1 + f('[') + g()]def"

In particular, braces do not need to be balanced:

特に、中かっこはバランスが取れている必要はありません:

    s/abc(?{ f('{'); })/def/

Even in a pattern that is interpolated and compiled at run-time, literal code blocks will be compiled once, at perl compile time; the following prints "ABCD":

実行時に展開されてコンパイルされるパターンの中であっても、 リテラルなコードブロックは perl のコンパイル時に一度だけコンパイルされます; 次のものは "ABCD" と表示されます:

    print "D";
    my $qr = qr/(?{ BEGIN { print "A" } })/;
    my $foo = "foo";
    /$foo$qr(?{ BEGIN { print "B" } })/;
    BEGIN { print "C" }

In patterns where the text of the code is derived from run-time information rather than appearing literally in a source code /pattern/, the code is compiled at the same time that the pattern is compiled, and for reasons of security, use re 'eval' must be in scope. This is to stop user-supplied patterns containing code snippets from being executable.

コードのテキストがソースコードの /pattern/ としてリテラルに現れるのではなく、 実行時の情報から派生したものであるパターンでは、 コードはパターンがコンパイルされるのと同時にコンパイルされ、 セキュリティー上の理由により、use re 'eval' が スコープ内になければなりません。 これは、実行可能なコード片を含む、ユーザーが提供したパターンを止めるためです。

In situations where you need to enable this with use re 'eval', you should also have taint checking enabled, if your perl supports it. Better yet, use the carefully constrained evaluation within a Safe compartment. See perlsec for details about both these mechanisms.

use re 'eval' でこれを有効にする必要がある場合、 perl が対応しているなら、汚染チェックも有効にするべきです。 出来れば、Safe 区画の中で注意深く制限された評価を使ってください。 これら両方の機構に関する詳細については perlsec を参照してください。

From the viewpoint of parsing, lexical variable scope and closures,

パース、レキシカル変数スコープ、クロージャの観点から、

    /AAA(?{ BBB })CCC/

behaves approximately like

はおよそ次のように振る舞います:

    /AAA/ && do { BBB } && /CCC/

Similarly,

同様に、

    qr/AAA(?{ BBB })CCC/

behaves approximately like

はおよそ次のように振る舞います:

    sub { /AAA/ && do { BBB } && /CCC/ }

In particular:

特に:

    { my $i = 1; $r = qr/(?{ print $i })/ }
    my $i = 2;
    /$r/; # prints "1"

Inside a (?{...}) block, $_ refers to the string the regular expression is matching against. You can also use pos() to know what is the current position of matching within this string.

(?{...}) ブロックの中では $_ は正規表現をマッチングさせている文字列を 参照します。 pos() を使ってこの文字列で現在のマッチング位置を知ることもできます。

The code block introduces a new scope from the perspective of lexical variable declarations, but not from the perspective of local and similar localizing behaviours. So later code blocks within the same pattern will still see the values which were localized in earlier blocks. These accumulated localizations are undone either at the end of a successful match, or if the assertion is backtracked (compare "Backtracking"). For example,

コードブロックは、local や同様のローカル化の振る舞いの観点 ではなく レキシカル変数宣言の観点での新しいスコープを導入します。 従って、同じパターンで後に出てくるコードブロックは 前に出てきたローカル化された値が見えるままです。 これらの蓄積されたローカル化は、マッチングが成功するか、 言明がバックトラックした時点で巻き戻されます ("Backtracking" と比較してください)。 例えば:

  $_ = 'a' x 8;
  m<
     (?{ $cnt = 0 })               # Initialize $cnt.
     (
       a
       (?{
           local $cnt = $cnt + 1;  # Update $cnt,
                                   # backtracking-safe.
       })
     )*
     aaaa
     (?{ $res = $cnt })            # On success copy to
                                   # non-localized location.
   >x;

will initially increment $cnt up to 8; then during backtracking, its value will be unwound back to 4, which is the value assigned to $res. At the end of the regex execution, $cnt will be wound back to its initial value of 0.

これはまず $cnt は 8 までインクリメントされます; それからバックトラックの間に、この値は 4 まで巻き戻され、 その値が $res に代入されます。 正規表現実行の最後では、$cnt は初期値である 0 に巻き戻ります。

This assertion may be used as the condition in a

この言明は条件として:

    (?(condition)yes-pattern|no-pattern)

switch. If not used in this way, the result of evaluation of code is put into the special variable $^R. This happens immediately, so $^R can be used from other (?{ code }) assertions inside the same regular expression.

スイッチとして使われるかもしれません。 この方法で使われなかったのなら、code の評価結果は特殊変数 $^R に おかれます。 これはすぐに行われるので $^R は同じ正規表現内の他の ?{ code }) 言明で使うことができます。

The assignment to $^R above is properly localized, so the old value of $^R is restored if the assertion is backtracked; compare "Backtracking".

この $^R への設定は適切にlocal化されるため、$^R の古い値は バックトラックしたときには復元されます; "Backtracking" を 見てください。

Note that the special variable $^N is particularly useful with code blocks to capture the results of submatches in variables without having to keep track of the number of nested parentheses. For example:

特殊変数 $^N は、一緒にネストしたかっこの数を数えずに一つ前の マッチング結果を捕捉するコードブロックで特に有用です。 例えば:

  $_ = "The brown fox jumps over the lazy dog";
  /the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i;
  print "color = $color, animal = $animal\n";

The use of this construct disables some optimisations globally in the pattern, and the pattern may execute much slower as a consequence. Use a * instead of the ? block to create an optimistic form of this construct. (*{ ... }) should not disable any optimisations.

この構文を使うと、グローバルにパターンの一部の最適化を無効化し、 結果としてパターンの実行は遙かに遅くなることがあります。 この構文の楽観的形式を作るために ? ブロックではなく * ブロックを使ってください。 (*{ ... }) はどの最適化も無効化しません。

(*{ code })

This is *exactly* the same as (?{ code }) with the exception that it does not disable any optimisations at all in the regex engine. How often it is executed may vary from perl release to perl release. In a failing match it may not even be executed at all.

これは、正規表現エンジンの どの 最適化も全く無効化しないことを除けば、 (?{ code }) と正確に同じです。 これがどれくらいの頻度で実行されるかは perl リリースによって異なります。 マッチングに失敗した場合は、全く実行されないこともあります。

(??{ code })

WARNING: Using this feature safely requires that you understand its limitations. Code executed that has side effects may not perform identically from version to version due to the effect of future optimisations in the regex engine. For more information on this, see "Embedded Code Execution Frequency".

警告: この機能を安全に使うには、その制限について理解することが必要です。 副作用を持つコードの実行は今後の正規表現エンジンの最適化の影響で バージョン間で必ずしも同じになるとは限らないでしょう。 これに関するさらなる情報については、"Embedded Code Execution Frequency" を 参照してください。

This is a "postponed" regular subexpression. It behaves in exactly the same way as a (?{ code }) code block as described above, except that its return value, rather than being assigned to $^R, is treated as a pattern, compiled if it's a string (or used as-is if its a qr// object), then matched as if it were inserted instead of this construct.

これは「先送りされた」正規部分表現です。 これは上述の (?{ code }) コードブロックと 正確に 同じように 振る舞いますが、その返り値は、$^R に代入されるのではなく、 パターンとして扱われ、 それが文字列の場合はコンパイルされ(あるいは qr// オブジェクトの場合は そのまま使われ)、それからこの構文の代わりに挿入されていたかのように マッチングします。

During the matching of this sub-pattern, it has its own set of captures which are valid during the sub-match, but are discarded once control returns to the main pattern. For example, the following matches, with the inner pattern capturing "B" and matching "BB", while the outer pattern captures "A";

副パターンのマッチングの間、副マッチングの間有効な独自の捕捉グループを 持ちますが、一旦制御が主パターンに戻ると捨てられます。 例えば、次のマッチングは、内側のパターンで "B" と "BB" にマッチングし、 一方外側のパターンは "A" を捕捉します;

    my $inner = '(.)\1';
    "ABBA" =~ /^(.)(??{ $inner })\1/;
    print $1; # prints "A";

Note that this means that there is no way for the inner pattern to refer to a capture group defined outside. (The code block itself can use $1, etc., to refer to the enclosing pattern's capture groups.) Thus, although

内側のパターンが外側で定義された捕捉グループを参照する方法は ないことに注意してください。 (コードブロック自体は、内側のパターンの捕捉グループを参照するために $1 などを使えます。) 従って:

    ('a' x 100)=~/(??{'(.)' x 100})/

will match, it will not set $1 on exit.

これはマッチング します が、終了時に $1 は設定 されません

The following pattern matches a parenthesized group:

次のパターンはかっこで囲まれたグループにマッチングします:

 $re = qr{
            \(
            (?:
               (?> [^()]+ )  # Non-parens without backtracking
             |
               (??{ $re })   # Group with matching parens
            )*
            \)
         }x;

See also (?PARNO) for a different, more efficient way to accomplish the same task.

同じタスクを行う別の、より効率的な方法として (?PARNO) も 参照してください。

Executing a postponed regular expression too many times without consuming any input string will also result in a fatal error. The depth at which that happens is compiled into perl, so it can be changed with a custom build.

入力を消費しない多すぎる先送りされた正規表現を実行するのも 致命的なエラーとなります。 これが起きる深度は perl にコンパイルされているので、カスタムビルドで これを変更できます。

The use of this construct disables some optimisations globally in the pattern, and the pattern may execute much slower as a consequence.

この構文を使うと、グローバルにパターンの一部の最適化を無効化し、 結果としてパターンの実行は遙かに遅くなることがあります。

(?PARNO) (?-PARNO) (?+PARNO) (?R) (?0)

Recursive subpattern. Treat the contents of a given capture buffer in the current pattern as an independent subpattern and attempt to match it at the current position in the string. Information about capture state from the caller for things like backreferences is available to the subpattern, but capture buffers set by the subpattern are not visible to the caller.

再帰部分パターン。 現在のパターンの与えられた捕捉バッファの内容を独立した 部分パターンとして扱って、 文字列の現在の位置でマッチングしようとします。 後方参照のような呼び出し元からの捕捉状態に関する情報は 部分パターンで利用可能ですが、 部分パターンで設定された捕捉バッファは呼び出し元には見えません。

Similar to (??{ code }) except that it does not involve executing any code or potentially compiling a returned pattern string; instead it treats the part of the current pattern contained within a specified capture group as an independent pattern that must match at the current position. Also different is the treatment of capture buffers, unlike (??{ code }) recursive patterns have access to their caller's match state, so one can use backreferences safely.

(??{ code }) と似ていますが、 コードの実行を伴なわず、返されたパターン文字列をコンパイルもしません; その代わりに、指定された捕捉グループに含まれる現在のパターンの一部を、 現在の位置でマッチングすべき独立したパターンとして扱います。 また、捕捉バッファの扱いも異なります; (??{ code }) と異なり、再帰パターンはその呼び出し元のマッチング 状態にアクセスすることが出来るので、安全に後方参照を使えます。

PARNO is a sequence of digits (not starting with 0) whose value reflects the paren-number of the capture group to recurse to. (?R) recurses to the beginning of the whole pattern. (?0) is an alternate syntax for (?R). If PARNO is preceded by a plus or minus sign then it is assumed to be relative, with negative numbers indicating preceding capture groups and positive ones following. Thus (?-1) refers to the most recently declared group, and (?+1) indicates the next group to be declared. Note that the counting for relative recursion differs from that of relative backreferences, in that with recursion unclosed groups are included.

PARNO はその値が再帰させる捕捉グループのかっこ番号を反映する一連の 数字からなります(そして 0 からは始まりません)。 (?R) はパターン全体の最初から再帰します。 (?0)(?R) の別の構文です。 PARNO の前に正符号または負符号がついていた場合には相対的な位置として 使われます; 負数であれば前の捕捉グループを、正数であれば続く 捕捉グループを示します。 従って (?-1) は一番最近宣言されたグループを参照し、(?+1) は次に 宣言されるグループを参照します。 相対再帰の数え方は相対後方参照とは違って、グループに閉じていない再帰は 含まれることに注意してください,

The following pattern matches a function foo() which may contain balanced parentheses as the argument.

以下のパターンは引数にバランスのとれたかっこを含んでいるかもしれない関数 foo() にマッチングします。

  $re = qr{ (                   # paren group 1 (full function)
              foo
              (                 # paren group 2 (parens)
                \(
                  (             # paren group 3 (contents of parens)
                  (?:
                   (?> [^()]+ ) # Non-parens without backtracking
                  |
                   (?2)         # Recurse to start of paren group 2
                  )*
                  )
                \)
              )
            )
          }x;

If the pattern was used as follows

このパターンを以下のように使うと,

    'foo(bar(baz)+baz(bop))'=~/$re/
        and print "\$1 = $1\n",
                  "\$2 = $2\n",
                  "\$3 = $3\n";

the output produced should be the following:

次のように出力されます:

    $1 = foo(bar(baz)+baz(bop))
    $2 = (bar(baz)+baz(bop))
    $3 = bar(baz)+baz(bop)

If there is no corresponding capture group defined, then it is a fatal error. Recursing deeply without consuming any input string will also result in a fatal error. The depth at which that happens is compiled into perl, so it can be changed with a custom build.

もし対応する捕捉グループが定義されていなかったときには致命的な エラーとなります。 入力を消費しない深い再帰も致命的なエラーとなります。 これが起きる深度は perl にコンパイルされているので、カスタムビルドで これを変更できます。

The following shows how using negative indexing can make it easier to embed recursive patterns inside of a qr// construct for later use:

以下に後で使うパターンのために、qr// 構成子内で再帰を埋め込むのに 負数の参照を使うとどのように容易になるかを示します:

    my $parens = qr/(\((?:[^()]++|(?-1))*+\))/;
    if (/foo $parens \s+ \+ \s+ bar $parens/x) {
       # do something here...
    }

Note that this pattern does not behave the same way as the equivalent PCRE or Python construct of the same form. In Perl you can backtrack into a recursed group, in PCRE and Python the recursed into group is treated as atomic. Also, modifiers are resolved at compile time, so constructs like (?i:(?1)) or (?:(?i)(?1)) do not affect how the sub-pattern will be processed.

補足 このパターンは PCRE や Python での等価な形式の構成子と同じように 振る舞うわけではありません。 Perl においては再帰グループの中にバックトラックできますが、PCRE や Python ではグループへの再帰はアトミックに扱われます。 また、修飾子はコンパイル時に解決されるので、(?i:(?1))(?:(?i)(?1)) といった構成子はサブパターンがどのように処理されたかに 影響されません。

(?&NAME)

Recurse to a named subpattern. Identical to (?PARNO) except that the parenthesis to recurse to is determined by name. If multiple parentheses have the same name, then it recurses to the leftmost.

名前付きサブパターンへの再帰。 再帰するかっこが名前によって決定される点以外は (?PARNO) と等価です。 もし複数のかっこで同じ名前を持っていた場合には一番左のものに再帰します。

It is an error to refer to a name that is not declared somewhere in the pattern.

パターンのどこでも宣言されていない名前の参照はエラーになります。

NOTE: In order to make things easier for programmers with experience with the Python or PCRE regex engines the pattern (?P>NAME) may be used instead of (?&NAME).

補足: Python または PCRE 正規表現エンジンに慣れているプログラマが 簡単になるように (?&NAME) の代わりに (?P>NAME) を 使うこともできます。

(?(condition)yes-pattern|no-pattern)
(?(condition)yes-pattern)

Conditional expression. Matches yes-pattern if condition yields a true value, matches no-pattern otherwise. A missing pattern always matches.

条件付き式。 condition が真なら yes-pattern にマッチングし、さもなければ no-pattern にマッチングします。 パターンがなければ常にマッチングします。

(condition) should be one of:

(condition) は次のいずれかです:

an integer in parentheses

(かっこでくるまれた数値)

(which is valid if the corresponding pair of parentheses matched);

(対応するかっこ対がマッチングしたときに有効);

a lookahead/lookbehind/evaluate zero-width assertion;

(先読み/後読み/ゼロ幅で評価される言明)

a name in angle brackets or single quotes

(角かっこもしくはシングルクォートでくるまれた名前)

(which is valid if a group with the given name matched);

(その名前のグループがマッチングしたときに有効);

the special symbol (R)

(特殊なシンボル (R))

(true when evaluated inside of recursion or eval). Additionally the "R" may be followed by a number, (which will be true when evaluated when recursing inside of the appropriate group), or by &NAME, in which case it will be true only when evaluated during recursion in the named group.

(再帰または eval 内で評価されているときに真)。 加えて "R" には数字(対応するグループ内で再帰しているときに真)、もしくは &NAME、こちらの時はその名前のグループで再帰している時にのみ真、を 続けることもできます。

Here's a summary of the possible predicates:

可能な述語の要約を次に示します:

(1) (2) ...

Checks if the numbered capturing group has matched something. Full syntax: (?(1)then|else)

その番号の捕捉グループが何かにマッチングしたかどうかを調べます。 完全な文法: (?(1)then|else)

(<NAME>) ('NAME')

Checks if a group with the given name has matched something. Full syntax: (?(<name>)then|else)

その名前のグループが何かにマッチングしたかどうかを調べます。 完全な文法: (?(<name>)then|else)

(?=...) (?!...) (?<=...) (?<!...)

Checks whether the pattern matches (or does not match, for the "!" variants). Full syntax: (?(?=lookahead)then|else)

パターンがマッチングするか (あるいは "!" 版はマッチングしないか) を チェックします。 完全な文法: (?(?=lookahead)then|else)

(?{ CODE })

Treats the return value of the code block as the condition. Full syntax: (?(?{ CODE })then|else)

コードブロックの返り値を条件として扱います。 完全な文法: (?(?{ CODE })then|else)

Note use of this construct may globally affect the performance of the pattern. Consider using (*{ CODE })

この構文を使うと、グローバルなパターンマッチングの性能に影響を与えます。 (*{ CODE }) を使うことを考慮してください。

(*{ CODE })

Treats the return value of the code block as the condition. Full syntax: (?(*{ CODE })then|else)

コードブロックの返り値を条件として扱います。 完全な構文: (?(*{ CODE })then|else)

(R)

Checks if the expression has been evaluated inside of recursion. Full syntax: (?(R)then|else)

式が再帰の中で評価されているかどうかを調べます。 完全な文法: (?(R)then|else)

(R1) (R2) ...

Checks if the expression has been evaluated while executing directly inside of the n-th capture group. This check is the regex equivalent of

式がその n 番目の捕捉グループのすぐ内側で実行されているかどうかを調べます。 これは次のものと等価な正規表現です

  if ((caller(0))[3] eq 'subname') { ... }

In other words, it does not check the full recursion stack.

言い換えると、これは完全な再帰スタックを調べるわけではありません。

Full syntax: (?(R1)then|else)

完全な文法: (?(R1)then|else)

(R&NAME)

Similar to (R1), this predicate checks to see if we're executing directly inside of the leftmost group with a given name (this is the same logic used by (?&NAME) to disambiguate). It does not check the full stack, but only the name of the innermost active recursion. Full syntax: (?(R&name)then|else)

(R1) と似ていて、この述語はその名前のつけられている一番左のグループの すぐ内側で実行されているかどうかをしらべます(一番左は (?&NAME) と 同じロジックです)。 これは完全なスタックを調べずに、一番内部のアクティブな再帰の名前だけを 調べます。 完全な文法: (?(R&name)then|else)

(DEFINE)

In this case, the yes-pattern is never directly executed, and no no-pattern is allowed. Similar in spirit to (?{0}) but more efficient. See below for details. Full syntax: (?(DEFINE)definitions...)

この場合において、yes-pattern は直接は実行されず、no-pattern は 許可されていません。 (?{0}) と似ていますがより効率的です。 詳細は次のようになります。 完全な文法: (?(DEFINE)definitions...)

For example:

例:

    m{ ( \( )?
       [^()]+
       (?(1) \) )
     }x

matches a chunk of non-parentheses, possibly included in parentheses themselves.

これはかっこ以外からなる固まりかかっこの中にあるそれらにマッチングします。

A special form is the (DEFINE) predicate, which never executes its yes-pattern directly, and does not allow a no-pattern. This allows one to define subpatterns which will be executed only by the recursion mechanism. This way, you can define a set of regular expression rules that can be bundled into any pattern you choose.

(DEFINE) は特殊な形式で、これはその yes-pattern を直接は実行せず、 no-pattern も許可していません。 これは再帰メカニズムの中で利用することでのみ実行されるサブパターンの 定義を許可します。 これによって、選んだパターンと一緒に正規表現ルールを定義できます。

It is recommended that for this usage you put the DEFINE block at the end of the pattern, and that you name any subpatterns defined within it.

この使い方において、DEFINE ブロックはパターンの最後におくこと、 そしてそこで定義する全てのサブパターンに名前をつけることが 推奨されています。

Also, it's worth noting that patterns defined this way probably will not be as efficient, as the optimizer is not very clever about handling them.

また、この方法によって定義されるパターンはその処理に関してそんなに 賢い訳ではないので効率的でないことに価値は何もないでしょう。

An example of how this might be used is as follows:

これをどのように使うかの例を次に示します:

  /(?<NAME>(?&NAME_PAT))(?<ADDR>(?&ADDRESS_PAT))
   (?(DEFINE)
     (?<NAME_PAT>....)
     (?<ADDRESS_PAT>....)
   )/x

Note that capture groups matched inside of recursion are not accessible after the recursion returns, so the extra layer of capturing groups is necessary. Thus $+{NAME_PAT} would not be defined even though $+{NAME} would be.

再帰の内側でマッチングした捕捉グループは再帰から戻った後には アクセスできないため、余分な捕捉グループの レイヤは必要な点に注意してください。 従って $+{NAME} が定義されていても $+{NAME_PAT} は定義されません。

Finally, keep in mind that subpatterns created inside a DEFINE block count towards the absolute and relative number of captures, so this:

最後に、DEFINE ブロックの内側で作られた副パターンは捕捉の絶対及び 相対番号で数えることに注意してください; 従ってこうすると:

    my @captures = "a" =~ /(.)                  # First capture
                           (?(DEFINE)
                               (?<EXAMPLE> 1 )  # Second capture
                           )/x;
    say scalar @captures;

Will output 2, not 1. This is particularly important if you intend to compile the definitions with the qr// operator, and later interpolate them in another pattern.

1 ではなく 2 を出力します。 これは、qr// 演算子で定義をコンパイルして、 後で他のパターンの中で展開することを意図している場合に特に重要です。

(?>pattern)
(*atomic:pattern)

An "independent" subexpression, one which matches the substring that a standalone pattern would match if anchored at the given position, and it matches nothing other than this substring. This construct is useful for optimizations of what would otherwise be "eternal" matches, because it will not backtrack (see "Backtracking"). It may also be useful in places where the "grab all you can, and do not give anything back" semantic is desirable.

「独立した」部分式、スタンドアロンの pattern がその場所に 固定されてマッチングする部分文字列にマッチングし、 その文字列以外にはなにもマッチングしません。 この構成子は他の"外部"マッチングになる最適化に便利です; なぜならこれはバックトラックしないためです("Backtracking" 参照)。 これは "できる限りを取り込んで、後は戻らない"セマンティクスが 必要な場所でも便利です。

For example: ^(?>a*)ab will never match, since (?>a*) (anchored at the beginning of string, as above) will match all characters "a" at the beginning of string, leaving no "a" for ab to match. In contrast, a*ab will match the same as a+b, since the match of the subgroup a* is influenced by the following group ab (see "Backtracking"). In particular, a* inside a*ab will match fewer characters than a standalone a*, since this makes the tail match.

例: ^(?>a*)ab は何もマッチングしません、 なぜなら (?>a*) (前述のように、文字列の開始で固定されます)は 文字列のはじめにある全ての文字 "a" にマッチングし、 ab のマッチングのための "a" を残さないためです。 対照的に、a*aba+b と同じようにマッチングします、 これはサブグループ a* のマッチングは次のグループ ab の影響を 受けるためです ("Backtracking" 参照)。 特に、a*ab の中の a* は単独の a* より短い文字にマッチングします; これによって最後のマッチングが行えるようになります。

(?>pattern) does not disable backtracking altogether once it has matched. It is still possible to backtrack past the construct, but not into it. So ((?>a*)|(?>b*))ar will still match "bar".

(?>pattern) は、一旦マッチングしたら、全くバックトラックを 無効にしません。 未だこの構文の前までバックトラックする可能性はありますが、構文の中に バックトラックすることはありません。 従って ((?>a*)|(?>b*))ar は "bar" にマッチングするままです。

An effect similar to (?>pattern) may be achieved by writing (?=(pattern))\g{-1}. This matches the same substring as a standalone a+, and the following \g{-1} eats the matched string; it therefore makes a zero-length assertion into an analogue of (?>...). (The difference between these two constructs is that the second one uses a capturing group, thus shifting ordinals of backreferences in the rest of a regular expression.)

(?>pattern) と似た効果は (?=(pattern))\g{-1} でも達成できます。 これは単独の a+ と同じ部分文字列にマッチングし、それに続く \g{-1} が マッチングした文字列を消費します; これはゼロ幅の言明が (?>...) の類似を作るためです。 (この2つの構成子は後者はグループをキャプチャするため、 それに続く正規表現の残りで後方参照の順序をずらす点で違いがあります。)

Consider this pattern:

次のパターンを考えてみてください:

    m{ \(
          (
            [^()]+           # x+
          |
            \( [^()]* \)
          )+
       \)
     }x

That will efficiently match a nonempty group with matching parentheses two levels deep or less. However, if there is no such group, it will take virtually forever on a long string. That's because there are so many different ways to split a long string into several substrings. This is what (.+)+ is doing, and (.+)+ is similar to a subpattern of the above pattern. Consider how the pattern above detects no-match on ((()aaaaaaaaaaaaaaaaaa in several seconds, but that each extra letter doubles this time. This exponential performance will make it appear that your program has hung. However, a tiny change to this pattern

これは 2 段階までのかっこでくるまれた空でないグループに効率的に マッチングします。 しかしながら、これはマッチングするグループがなかったときに長い 文字列においてはほとんど永遠に戻りません。 これは長い文字列をいくつかの部分文字列に分解する方法がいくつもあるためです。 これは (.+)+ が行うことでもあり、(.+)+ は このパターンの 部分パターンと似ています。 このパターンが ((()aaaaaaaaaaaaaaaaaa にはマッチングしないことを どうやって検出するかを少し考えてみましょう、 しかしここでは余計な文字を2倍にしてみます。 この指数的なパフォーマンスはプログラムのハングアップとして表面化します。 しかしながら、このパターンに小さな変更をいれてみます,

    m{ \(
          (
            (?> [^()]+ )        # change x+ above to (?> x+ )
          |
            \( [^()]* \)
          )+
       \)
     }x

which uses (?>...) matches exactly when the one above does (verifying this yourself would be a productive exercise), but finishes in a fourth the time when used on a similar string with 1000000 "a"s. Be aware, however, that, when this construct is followed by a quantifier, it currently triggers a warning message under the use warnings pragma or -w switch saying it "matches null string many times in regex".

これは上で行っているように (?>...) マッチングを 使っています(これは自身で確認してみるとよいでしょう)が、 しかし 1000000 個の "a" からなる似た文字列を使ってみると、4 分の 1 の 時間で完了します。 しかしながら、この構文は量指定子が引き続くと現在のところ use warnings プラグマまたは -w スイッチの影響下では "matches null string many times in regex" (正規表現において空文字列に何回もマッチングしました) という警告を 発するでしょう。

On simple groups, such as the pattern (?> [^()]+ ), a comparable effect may be achieved by negative lookahead, as in [^()]+ (?! [^()] ). This was only 4 times slower on a string with 1000000 "a"s.

パターン (?> [^()]+ ) のような簡単なグループでは、 比較できる影響は [^()]+ (?! [^()] ) のように負の先読みの 言明で達することができます。 これは 1000000 個の "a" からなる文字列において 4 倍だけ遅くなります。

The "grab all you can, and do not give anything back" semantic is desirable in many situations where on the first sight a simple ()* looks like the correct solution. Suppose we parse text with comments being delimited by "#" followed by some optional (horizontal) whitespace. Contrary to its appearance, #[ \t]* is not the correct subexpression to match the comment delimiter, because it may "give up" some whitespace if the remainder of the pattern can be made to match that way. The correct answer is either one of these:

最初の ()* のような正しい解法となる多くの状況において 「できる限りを取り込んで、後は戻らない」セマンティクスが望まれるものです。 任意で(水平)空白の続く "#" によって区切られるコメントのついたテキストの パースを考えてみます。 その出現と対比して、#[ \t]* はコメント区切りにマッチングする 正しい部分式ではありません; なぜならパターンの残りがそれのマッチングを 作ることができるのならそれはいくつかの空白を「あきらめてしまう」ためです。 正しい回答は以下のいずれかです:

    (?>#[ \t]*)
    #[ \t]*(?![ \t])

For example, to grab non-empty comments into $1, one should use either one of these:

例えば空でないコメントを $1 に取り込むためには次のいずれかを使います:

    / (?> \# [ \t]* ) (        .+ ) /x;
    /     \# [ \t]*   ( [^ \t] .* ) /x;

Which one you pick depends on which of these expressions better reflects the above specification of comments.

選んだ方はコメントの仕様をより適切に反映した式に依存します。

In some literature this construct is called "atomic matching" or "possessive matching".

いくつかの書籍においてこの構成子は「アトミックなマッチング」 または「絶対最大マッチング(possessive matching)」と呼ばれます。

Possessive quantifiers are equivalent to putting the item they are applied to inside of one of these constructs. The following equivalences apply:

絶対最大量指定子はそれが適用されている項目をこれらの構成子の中に置くことと 等価です。 以下の等式が適用されます:

    Quantifier Form     Bracketing Form
    ---------------     ---------------
    PAT*+               (?>PAT*)
    PAT++               (?>PAT+)
    PAT?+               (?>PAT?)
    PAT{min,max}+       (?>PAT{min,max})

Nested (?>...) constructs are not no-ops, even if at first glance they might seem to be. This is because the nested (?>...) can restrict internal backtracking that otherwise might occur. For example,

ネストした (?>...) 構文は、 たとえ一見何もしないように見えても、何もしないものではありません。 これは、ネストした (?>...) は、なければ起きるかもしれない 内部バックトラックを制限するからです。 例えば:

 "abc" =~ /(?>a[bc]*c)/

matches, but

これはマッチングしますが:

 "abc" =~ /(?>a(?>[bc]*)c)/

does not.

これはマッチングしません。

(?[ ])

"Extended Bracketed Character Classes" in perlrecharclass を参照してください。

バックトラック

NOTE: This section presents an abstract approximation of regular expression behavior. For a more rigorous (and complicated) view of the rules involved in selecting a match among possible alternatives, see "Combining RE Pieces".

補足: このセクションでは正規表現の振る舞いに関する抽象的な概要を 説明します。 可能な代替におけるマッチングの選択におけるルールの厳密な(そして複雑な) 説明は "Combining RE Pieces" を参照してください。

A fundamental feature of regular expression matching involves the notion called backtracking, which is currently used (when needed) by all regular non-possessive expression quantifiers, namely "*", *?, "+", +?, {n,m}, and {n,m}?. Backtracking is often optimized internally, but the general principle outlined here is valid.

正規表現マッチングの基本的な機能には最近(必要であれば)すべての強欲でない 正規表現量指定子、つまり、 "*", *?, "+", +?, {n,m}, {n,m}? で 使われる バックトラッキング と呼ばれる概念が含まれています。 バックトラックはしばしば内部で最適化されますが、ここで概説する一般的な 原則は妥当です。

For a regular expression to match, the entire regular expression must match, not just part of it. So if the beginning of a pattern containing a quantifier succeeds in a way that causes later parts in the pattern to fail, the matching engine backs up and recalculates the beginning part--that's why it's called backtracking.

正規表現がマッチングする時、その正規表現の一部ではなく、 全体 がマッチングしなければなりません。 そのためもしパターンの前半にパターンの後半部分を失敗させてしまう 量指定子が含まれているのなら、マッチングングエンジンはいったん戻って 開始位置を再計算します -- これがバックトラッキングと呼ばれる所以です。

Here is an example of backtracking: Let's say you want to find the word following "foo" in the string "Food is on the foo table.":

バックトラッキングの例をあげてみます: "Food is on the foo table." という 文字列の中で "foo" に続く単語を取り出してください:

    $_ = "Food is on the foo table.";
    if ( /\b(foo)\s+(\w+)/i ) {
        print "$2 follows $1.\n";
    }

When the match runs, the first part of the regular expression (\b(foo)) finds a possible match right at the beginning of the string, and loads up $1 with "Foo". However, as soon as the matching engine sees that there's no whitespace following the "Foo" that it had saved in $1, it realizes its mistake and starts over again one character after where it had the tentative match. This time it goes all the way until the next occurrence of "foo". The complete regular expression matches this time, and you get the expected output of "table follows foo."

マッチングが実行される時、正規表現の最初の部分 (\b(foo)) は開始文字列の 右側で可能なマッチングを探します; そして $1 に "Foo" をロードします。 しかし、すぐにマッチングエンジンは $1 に保存した "Foo" の後に空白が 無いことを見つけ、それが失敗だったことを検出して仮にマッチングさせた 場所の 1 文字後から開始します。 この時次の "foo" の出現まで進みます。 この時に正規表現は完全にマッチングし、予測した出力 "table follows foo." を 得ます。

Sometimes minimal matching can help a lot. Imagine you'd like to match everything between "foo" and "bar". Initially, you write something like this:

最小マッチングが役立つこともあります。 "foo" と "bar" の間の全てにマッチングしたいと考えてください。 最初に、次のように書くかもしれません:

    $_ =  "The food is under the bar in the barn.";
    if ( /foo(.*)bar/ ) {
        print "got <$1>\n";
    }

Which perhaps unexpectedly yields:

しかしこれは考えたのと違う結果となるでしょう:

  got <d is under the bar in the >

That's because .* was greedy, so you get everything between the first "foo" and the last "bar". Here it's more effective to use minimal matching to make sure you get the text between a "foo" and the first "bar" thereafter.

これは .* が貪欲であり、そのために 最初の "foo" と 最後の "bar" の間にある全てを取り出してしまいます。 次に "foo" とその後の最初の "bar" の間にあるテキストを取り出す 最小マッチングを使ったもっと効率的な方法を示します:

    if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
  got <d is under the >

Here's another example. Let's say you'd like to match a number at the end of a string, and you also want to keep the preceding part of the match. So you write this:

別の例も出してみます。 文字列の最後にある数字にマッチングさせて、そのマッチングの前の部分も 保持させてみましょう。 そしてあなたは次のように書くかもしれません。

    $_ = "I have 2 numbers: 53147";
    if ( /(.*)(\d*)/ ) {                                # Wrong!
        print "Beginning is <$1>, number is <$2>.\n";
    }

That won't work at all, because .* was greedy and gobbled up the whole string. As \d* can match on an empty string the complete regular expression matched successfully.

これは全く動作しません、なぜなら .* は貪欲であり文字列全体を 飲み込んでしまいます。 \d* は空の文字列にマッチングできるので正規表現は完全に正常に マッチングします。

    Beginning is <I have 2 numbers: 53147>, number is <>.

Here are some variants, most of which don't work:

動作しない主なバリエーションをあげておきます:

    $_ = "I have 2 numbers: 53147";
    @pats = qw{
        (.*)(\d*)
        (.*)(\d+)
        (.*?)(\d*)
        (.*?)(\d+)
        (.*)(\d+)$
        (.*?)(\d+)$
        (.*)\b(\d+)$
        (.*\D)(\d+)$
    };

    for $pat (@pats) {
        printf "%-12s ", $pat;
        if ( /$pat/ ) {
            print "<$1> <$2>\n";
        } else {
            print "FAIL\n";
        }
    }

That will print out:

これらの結果は次のようになります:

    (.*)(\d*)    <I have 2 numbers: 53147> <>
    (.*)(\d+)    <I have 2 numbers: 5314> <7>
    (.*?)(\d*)   <> <>
    (.*?)(\d+)   <I have > <2>
    (.*)(\d+)$   <I have 2 numbers: 5314> <7>
    (.*?)(\d+)$  <I have 2 numbers: > <53147>
    (.*)\b(\d+)$ <I have 2 numbers: > <53147>
    (.*\D)(\d+)$ <I have 2 numbers: > <53147>

As you see, this can be a bit tricky. It's important to realize that a regular expression is merely a set of assertions that gives a definition of success. There may be 0, 1, or several different ways that the definition might succeed against a particular string. And if there are multiple ways it might succeed, you need to understand backtracking to know which variety of success you will achieve.

このように、これは幾分トリッキーです。 重要なのは正規表現は成功の定義を定める主張の集合にすぎないことを 認識することです。 特定の文字列で成功となる定義には 0, 1 または複数の違ったやり方が存在します。 そしてもし成功する複数の方法が存在するのなら成功したうちのどれが目的と するものなのかを知るためにバックトラッキングを理解しておく必要があります。

When using lookahead assertions and negations, this can all get even trickier. Imagine you'd like to find a sequence of non-digits not followed by "123". You might try to write that as

先読みの言明及び否定を使っている時にはこれはますますトリッキーになります。 "123" が後ろに続かない数字以外の列を探したいと考えてみてください。 あなたは次のように書くかもしれません。

    $_ = "ABC123";
    if ( /^\D*(?!123)/ ) {                # Wrong!
        print "Yup, no 123 in $_\n";
    }

But that isn't going to match; at least, not the way you're hoping. It claims that there is no 123 in the string. Here's a clearer picture of why that pattern matches, contrary to popular expectations:

ですがこれはマッチングしません; 少なくともなってほしかったようには。 これは文字列の中に 123 がないことを要求します。 よくある予想と比較してなぜパターンがマッチングするのかのわかりやすい 説明を次に示します:

    $x = 'ABC123';
    $y = 'ABC445';

    print "1: got $1\n" if $x =~ /^(ABC)(?!123)/;
    print "2: got $1\n" if $y =~ /^(ABC)(?!123)/;

    print "3: got $1\n" if $x =~ /^(\D*)(?!123)/;
    print "4: got $1\n" if $y =~ /^(\D*)(?!123)/;

This prints

これは次の出力となります

    2: got ABC
    3: got AB
    4: got ABC

You might have expected test 3 to fail because it seems to a more general purpose version of test 1. The important difference between them is that test 3 contains a quantifier (\D*) and so can use backtracking, whereas test 1 will not. What's happening is that you've asked "Is it true that at the start of $x, following 0 or more non-digits, you have something that's not 123?" If the pattern matcher had let \D* expand to "ABC", this would have caused the whole pattern to fail.

テスト 3 はテスト 1 のより一般的なバージョンなのでそれが失敗すると 考えたかもしれません。 この 2 つの重要な違いは、テスト 3 には量指定子(\D*)が含まれているので テスト1ではできなかったバックトラッキングを行うことが できるところにあります。 ここであなたは「$x のはじめで 0 個以上の非数字があるから 123 ではない 何かを得られるんじゃないの?」と聞くでしょう。 このパターンマッチングが \D* を "ABC" に展開させると これはパターン全体を失敗させることになります。

The search engine will initially match \D* with "ABC". Then it will try to match (?!123) with "123", which fails. But because a quantifier (\D*) has been used in the regular expression, the search engine can backtrack and retry the match differently in the hope of matching the complete regular expression.

探索エンジンは最初に \D* を "ABC" にマッチングさせます。 そして (?!123) を "123" にマッチングさせ、これは失敗します。 けれども量指定子 (\D*) が正規表現の中で使われているので、探索エンジンは バックトラックしてこの正規表現全体をマッチングさせるように異なるマッチングを 行うことができます。

The pattern really, really wants to succeed, so it uses the standard pattern back-off-and-retry and lets \D* expand to just "AB" this time. Now there's indeed something following "AB" that is not "123". It's "C123", which suffices.

このパターンは本当に、本当に 成功したいので、これは標準的なパターンの 後退再試行を行い、この時に \D* を "AB" のみに展開させます。 そして確かに "AB" の後ろは "123" ではありません。 "C123" は十分満たしています。

We can deal with this by using both an assertion and a negation. We'll say that the first part in $1 must be followed both by a digit and by something that's not "123". Remember that the lookaheads are zero-width expressions--they only look, but don't consume any of the string in their match. So rewriting this way produces what you'd expect; that is, case 5 will fail, but case 6 succeeds:

これは言明と否定の両方を使うことで処理することができます。 $1 の最初の部分は数字が続きかつそれは "123" ではないことを宣言します。 先読みはゼロ幅の式なのでそれがマッチングした文字列を全く消費しないことを 思い出してください。 そしてこれを必要なものを生成するように書き換えます; つまり、5 のケースでは失敗し、6 のケースは成功します:

    print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/;
    print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/;

    6: got ABC

In other words, the two zero-width assertions next to each other work as though they're ANDed together, just as you'd use any built-in assertions: /^$/ matches only if you're at the beginning of the line AND the end of the line simultaneously. The deeper underlying truth is that juxtaposition in regular expressions always means AND, except when you write an explicit OR using the vertical bar. /ab/ means match "a" AND (then) match "b", although the attempted matches are made at different positions because "a" is not a zero-width assertion, but a one-width assertion.

言い換えると、このそれぞれの次にある2つのゼロ幅の言明はちょうど何か組み込みの 言明を使ったかのようにそれらがともに AND されているかのように動作します: /^$/ は行の始まりで且つ同時に行の終了でる時にのみマッチングします。 もっと深部での真実は、併記された正規表現は垂直線を使って明示的に OR を 書いたとき以外は常に AND を意味します。 /ab/ は、"a" がゼロ幅の言明ではなく 1 文字幅の言明なので異なる場所で マッチングが行われはしますが、 "a" にマッチング且つ(そして) "b" に マッチングということを意味します。

WARNING: Particularly complicated regular expressions can take exponential time to solve because of the immense number of possible ways they can use backtracking to try for a match. For example, without internal optimizations done by the regular expression engine, this will take a painfully long time to run:

警告: 特にコンパイルされた正規表現はマッチングのために できる限りのバックトラックを非常に多くの回数行うので 解くために指数的な時間を必要とすることがあります。 例えば、正規表現エンジンの内部で行われる最適化がなかったときには、次の評価は 尋常じゃないくらい長時間かかります:

    'aaaaaaaaaaaa' =~ /((a{0,5}){0,5})*[c]/

And if you used "*"'s in the internal groups instead of limiting them to 0 through 5 matches, then it would take forever--or until you ran out of stack space. Moreover, these internal optimizations are not always applicable. For example, if you put {0,5} instead of "*" on the external group, no current optimization is applicable, and the match takes a long time to finish.

そしてもし内側のグループで 0 から 5 回にマッチングを制限する代わりに "*" を使うと、永久に、またはスタックを使い果たすまで 実行し続けることになります。 その上、これらの最適化は常にできるわけではありません。 例えば、外側のグループで "*" の代わりに {0,5} を使ったときに、現在の 最適化は適用されません; そしてマッチングが終わるまでの長い時間が 必要になります。

A powerful tool for optimizing such beasts is what is known as an "independent group", which does not backtrack (see "(?>pattern)"). Note also that zero-length lookahead/lookbehind assertions will not backtrack to make the tail match, since they are in "logical" context: only whether they match is considered relevant. For an example where side-effects of lookahead might have influenced the following match, see "(?>pattern)".

そのような野獣のような最適化のためのパワフルなツールとして 知られているものに、「独立グループ」があります; これはバックトラックを 行いません ("(?>pattern)" を参照)。 ゼロ幅の先読み/後読みの言明も「論理的な」文脈なので末尾のマッチングを バックトラックしません: マッチングが関連して考慮されるかどうかだけです。 先読みの言明の副作用がそれに続くマッチングに影響する かもしれない 例は、 "(?>pattern)" を参照してください。

用字並び

A script run is basically a sequence of characters, all from the same Unicode script (see "Scripts" in perlunicode), such as Latin or Greek. In most places a single word would never be written in multiple scripts, unless it is a spoofing attack. An infamous example, is

用字連続は基本的には、ラテン文字やギリシャ文字のような、 全て同じ Unicode 用字 ("Scripts" in perlunicode 参照) からの文字の並びです。 ほとんどの場所では、なりすまし攻撃でない限り、一つの単語は決して複数の用字で 書かれることはありません。 悪名高い例は次のものです:

 paypal.com

Those letters could all be Latin (as in the example just above), or they could be all Cyrillic (except for the dot), or they could be a mixture of the two. In the case of an internet address the .com would be in Latin, And any Cyrillic ones would cause it to be a mixture, not a script run. Someone clicking on such a link would not be directed to the real Paypal website, but an attacker would craft a look-alike one to attempt to gather sensitive information from the person.

これらの文字は全て (直前のように) ラテン文字かもしれませんし、 (ドットを除いて) 全てキリル文字かもしれませんし、二つの混合かも しれません。 インターネットアドレスの場合、.com はラテン文字で、 キリル文字は混合となり用字連続ではありません。 誰かがこのようなリンクをクリックすると、本当の Paypal ウェブサイトに 移動せず、攻撃者がその人から機微情報を集めようとするために 見た目が似たものを細工するかもしれません。

Starting in Perl 5.28, it is now easy to detect strings that aren't script runs. Simply enclose just about any pattern like either of these:

Perl 5.28 から、用字連続でない文字列を簡単に検出できるようになりました。 単にパターンを次のどちらかのような形で囲みます:

 (*script_run:pattern)
 (*sr:pattern)

What happens is that after pattern succeeds in matching, it is subjected to the additional criterion that every character in it must be from the same script (see exceptions below). If this isn't true, backtracking occurs until something all in the same script is found that matches, or all possibilities are exhausted. This can cause a lot of backtracking, but generally, only malicious input will result in this, though the slow down could cause a denial of service attack. If your needs permit, it is best to make the pattern atomic to cut down on the amount of backtracking. This is so likely to be what you want, that instead of writing this:

pattern がマッチングした後に次のことが起きます; その中の全ての文字が同じ用字であるという追加の条件が課されます (後述する例外参照)。 これが真でない場合、全て同じ用字でマッチングする何かが見つかるか、 全ての可能性がなくなるまで、バックトラッキングが発生します。 これは多くのバックトラッキングを引き起こしますが、一般的に、 悪意のある入力だけがこれを引き起こします; しかし、この速度低下はサービス不能攻撃を引き起こすかもしれません。 事情が許すなら、バックトラッキングの量を減らすためにパターンを アトミックに書くのが最善です。 これはおそらくあなたが求めているものなので、次のように書く代わりに:

 (*script_run:(?>pattern))

you can write either of these:

次のどちらかのように書けます:

 (*atomic_script_run:pattern)
 (*asr:pattern)

(See "(?>pattern)".)

("(?>pattern)" を参照してください。)

In Taiwan, Japan, and Korea, it is common for text to have a mixture of characters from their native scripts and base Chinese. Perl follows Unicode's UTS 39 (https://unicode.org/reports/tr39/) Unicode Security Mechanisms in allowing such mixtures. For example, the Japanese scripts Katakana and Hiragana are commonly mixed together in practice, along with some Chinese characters, and hence are treated as being in a single script run by Perl.

台湾、日本、韓国では、独自の用字からの文字と中国語を基にした文字が 混合している文章は一般的です。 Perl はこのような混合を許すために Unicode の UTS 39 (https://unicode.org/reports/tr39/) Unicode Security Mechanisms に 従います。 例えば、日本語用字のカタカナとひらがなは実際には一部の中国語文字と共に 混合しているのが一般的なので、Perl によって単一の用字連続として 扱われます。

The rules used for matching decimal digits are slightly stricter. Many scripts have their own sets of digits equivalent to the Western 0 through 9 ones. A few, such as Arabic, have more than one set. For a string to be considered a script run, all digits in it must come from the same set of ten, as determined by the first digit encountered. As an example,

10 進数字とマッチングするために使われる規則は少し厳密になります。 多くの用字は、西洋の 0 から 9 と等価な独自の数字の集合を持ちます。 アラビア文字のように、複数の集合を持つものもあります。 用字連続が考慮される文字列については、全ての数字は、遭遇した 最初の数字で決定されるものと同じ集合でなければなりません。 例えば:

 qr/(*script_run: \d+ \b )/x

guarantees that the digits matched will all be from the same set of 10. You won't get a look-alike digit from a different script that has a different value than what it appears to be.

これはマッチングした数字が全て同じ集合の 10 文字からであることを保証します。 見た目と異なる値を持つ、異なる用字からの数字に見えるものを得ることは ありません。

Unicode has three pseudo scripts that are handled specially.

Unicode には特別に扱われる三つの疑似用字があります。

"Unknown" is applied to code points whose meaning has yet to be determined. Perl currently will match as a script run, any single character string consisting of one of these code points. But any string longer than one code point containing one of these will not be considered a script run.

"Unknown" は、意味がまだ決定されていない符号位置に適用されます。 Perl は現在の所それらのうちの一つの符号位置からなる 1 文字文字列を 用字連続としてマッチングします。 しかし、それらの一つを含む 2 符号位置以上の文字列は用字連続として 扱われません。

"Inherited" is applied to characters that modify another, such as an accent of some type. These are considered to be in the script of the master character, and so never cause a script run to not match.

"Inherited" は、一部のアクセントのように、他のものを変更する文字に 適用されます。 これらは元の文字の用字として扱われるので、 マッチングしない用字連続になることはありません。

The other one is "Common". This consists of mostly punctuation, emoji, characters used in mathematics and music, the ASCII digits 0 through 9, and full-width forms of these digits. These characters can appear intermixed in text in many of the world's scripts. These also don't cause a script run to not match. But like other scripts, all digits in a run must come from the same set of 10.

もう一つは "Common" です。 これはほとんど句読点、絵文字、数学と音楽で使われる文字、 ASCII の数字 0 から 9、およびそれらの全角版 で構成されます。 これらの文字は世界中の多くの用字の文章で混ぜられて現れます。 これらもまた、マッチングしない用字連続にはなりません。 しかし他の幼児と同様、連続の中の全ての数字は 10 の同じ集合からの ものでなければなりません。

This construct is non-capturing. You can add parentheses to pattern to capture, if desired. You will have to do this if you plan to use "(*ACCEPT) (*ACCEPT:arg)" and not have it bypass the script run checking.

この構文は捕捉しません。 捕捉したい場合は、その pattern にかっこを追加できます。 "(*ACCEPT) (*ACCEPT:arg)" を使う予定で、用字連続チェックを 迂回しない場合は、こうすることが必要でしょう。

The Script_Extensions property as modified by UTS 39 (https://unicode.org/reports/tr39/) is used as the basis for this feature.

この機能の基礎としては、UTS 39 (https://unicode.org/reports/tr39/) によって 修正された Script_Extensions 特性が使われます。

To summarize,

まとめると:

  • All length 0 or length 1 sequences are script runs.

    全ての長さ 0 または長さ 1 の並びは用字連続です。

  • A longer sequence is a script run if and only if all of the following conditions are met:

    より長い並びは、以下の条件の 全て に合致した場合にのみ用字連続です:

    1. No code point in the sequence has the Script_Extension property of Unknown.

      並びの中に Script_Extension 特性が Unknown の符号位置がない。

      This currently means that all code points in the sequence have been assigned by Unicode to be characters that aren't private use nor surrogate code points.

      これは現在の所、並びの中の全ての符号位置は、私用領域やサロゲート 符号位置でない、文字として Unicode によって割り当てられていることを 意味します。

    2. All characters in the sequence come from the Common script and/or the Inherited script and/or a single other script.

      並びの全ての文字は、Common 用字と Inherited 用字とその他の単一の用字の いずれかである。

      The script of a character is determined by the Script_Extensions property as modified by UTS 39 (https://unicode.org/reports/tr39/), as described above.

      文字の用字は、前述の UTS 39 (https://unicode.org/reports/tr39/) で 修正された Script_Extensions 特性によって決定されます。

    3. All decimal digits in the sequence come from the same block of 10 consecutive digits.

      並びの全ての 10 進数字は 10 の連続した数字の同じブロックからの ものである。

特殊なバックトラック制御記号

These special patterns are generally of the form (*VERB:arg). Unless otherwise stated the arg argument is optional; in some cases, it is mandatory.

これらの特殊なパターンは (*VERB:arg) という一般形式を持っています。 特に記されていない限り、arg はオプションです; 一部の場合では、 これは必須です。

Any pattern containing a special backtracking verb that allows an argument has the special behaviour that when executed it sets the current package's $REGERROR and $REGMARK variables. When doing so the following rules apply:

引数を許可する特殊バックトラック制御記号を含んでいる全てのパターンは、 それが実行されると現在のパッケージの $REGERROR 及び $REGMARK 変数を 設定する特殊な振る舞いを持っています。 これが行われる時以下の手順が適用されます。

On failure, the $REGERROR variable will be set to the arg value of the verb pattern, if the verb was involved in the failure of the match. If the arg part of the pattern was omitted, then $REGERROR will be set to the name of the last (*MARK:NAME) pattern executed, or to TRUE if there was none. Also, the $REGMARK variable will be set to FALSE.

失敗時には $REGERROR 変数には、記号がマッチングの失敗の中で 使われていたのならその記号パターンの arg の値がセットされます。 もしパターンの arg 部分が省略されていたときには、$REGERROR には 最後に実行された (*MARK:NAME) パターンの名前、またはそれもなければ 真に設定されます。 また、$REGMARK 変数は偽に設定されます。

On a successful match, the $REGERROR variable will be set to FALSE, and the $REGMARK variable will be set to the name of the last (*MARK:NAME) pattern executed. See the explanation for the (*MARK:NAME) verb below for more details.

マッチングの成功時には、$REGERROR 変数は偽に設定され、$REGMARK 変数には 最後に実行された (*MARK:NAME) パターンの名前が設定されます。 詳細は (*MARK:NAME) 記号の説明を参照してください。

NOTE: $REGERROR and $REGMARK are not magic variables like $1 and most other regex-related variables. They are not local to a scope, nor readonly, but instead are volatile package variables similar to $AUTOLOAD. They are set in the package containing the code that executed the regex (rather than the one that compiled it, where those differ). If necessary, you can use local to localize changes to these variables to a specific scope before executing a regex.

補足: $REGERROR 及び $REGMARK$1 や他の多くの 正規表現関連の変数のようにマジック変数ではありません。 それらはスコープ内にローカルにならず、読み込み専用でもありませんが、 $AUTOLOAD と似た揮発するパッケージ変数です。 これらには正規表現が 実行される コードを含むパッケージが設定されます (コンパイルされるコードではありません; これは異なることがあります)。 必要な場合は、正規表現を実行する前に これらの変数の変更を特定のスコープ内に留めるために local を使えます。

If a pattern does not contain a special backtracking verb that allows an argument, then $REGERROR and $REGMARK are not touched at all.

もしパターンが引数を許可する特殊バックトラック記号を含んでなかった場合には、 $REGERROR 及び $REGMARK は全く触られません。

Verbs

(動詞)

(*PRUNE) (*PRUNE:NAME)

This zero-width pattern prunes the backtracking tree at the current point when backtracked into on failure. Consider the pattern /A (*PRUNE) B/, where A and B are complex patterns. Until the (*PRUNE) verb is reached, A may backtrack as necessary to match. Once it is reached, matching continues in B, which may also backtrack as necessary; however, should B not match, then no further backtracking will take place, and the pattern will fail outright at the current starting position.

このゼロ幅のパターンは失敗でバックトラックしてきたときに現在の位置で バックトラックツリーを刈り取ります。 /A (*PRUNE) B/ というパターンで AB も複雑なパターンである時を 考えてみます。 (*PRUNE) に達するまでは、A はマッチングに必要であれば バックトラックしていきます。 しかし一旦そこに達して B に続くと、そこでも必要に応じてバックトラックします; しかしながら、B がマッチングしなかったときにはそれ以上のバックトラックは 行われず、現在の開始位置でのマッチングはすぐに失敗します。

The following example counts all the possible matching strings in a pattern (without actually matching any of them).

次の例ではパターンに対してマッチングできるすべての文字列を(実際には マッチングさせずに)数えます。

    'aaab' =~ /a+b?(?{print "$&\n"; $count++})(*FAIL)/;
    print "Count=$count\n";

which produces:

この出力:

    aaab
    aaa
    aa
    a
    aab
    aa
    a
    ab
    a
    Count=9

If we add a (*PRUNE) before the count like the following

次のように数える前に (*PRUNE) を加えると

    'aaab' =~ /a+b?(*PRUNE)(?{print "$&\n"; $count++})(*FAIL)/;
    print "Count=$count\n";

we prevent backtracking and find the count of the longest matching string at each matching starting point like so:

バックトラックを妨げ次のように各開始位置での一番長いマッチング文字列を 数えるようになります:

    aaab
    aab
    ab
    Count=3

Any number of (*PRUNE) assertions may be used in a pattern.

1つのパターン内で (*PRUNE) 言明はいくつでも使えます。

See also "(?>pattern)" and possessive quantifiers for other ways to control backtracking. In some cases, the use of (*PRUNE) can be replaced with a (?>pattern) with no functional difference; however, (*PRUNE) can be used to handle cases that cannot be expressed using a (?>pattern) alone.

バックトラックを制御する他の方法として "(?>pattern)" 及び絶対最大量指定子も参照してください。 幾つかのケースにおいては (*PRUNE) の利用は機能的な違いなしに (?>pattern) で置き換えることができます; しかしながら (*PRUNE)(?>pattern) 単独では表現できないケースを扱うために使えます。

(*SKIP) (*SKIP:NAME)

This zero-width pattern is similar to (*PRUNE), except that on failure it also signifies that whatever text that was matched leading up to the (*SKIP) pattern being executed cannot be part of any match of this pattern. This effectively means that the regex engine "skips" forward to this position on failure and tries to match again, (assuming that there is sufficient room to match).

このゼロ幅のパターンは *PRUNE と似ていますが、実行されている (*SKIP) パターンまでにマッチングしたテキストはこのパターンの どのマッチングの一部にもならないことを示します。 これは正規表現エンジンがこの位置まで失敗として「スキップ」して(マッチングに 十分な空間があれば)再びマッチングを試みることを効率的に意味します。

The name of the (*SKIP:NAME) pattern has special significance. If a (*MARK:NAME) was encountered while matching, then it is that position which is used as the "skip point". If no (*MARK) of that name was encountered, then the (*SKIP) operator has no effect. When used without a name the "skip point" is where the match point was when executing the (*SKIP) pattern.

(*SKIP:NAME) パターンの名前部分には特別な意味があります。 もしマッチングにおいて (*MARK:NAME) に遭遇すると、それは「スキップ 位置」として使われる位置になります。 その名前の (*MARK) と東宮していなければ、(*SKIP) 操作は効果を 持ちません。 名前がなければ「スキップ位置」は (*SKIP) パターンの実行されたときに マッチングポイントが使われます。

Compare the following to the examples in (*PRUNE); note the string is twice as long:

以下の例を (*PRUNE) と比べてみてください; 文字列が2倍になってることに注意してください:

 'aaabaaab' =~ /a+b?(*SKIP)(?{print "$&\n"; $count++})(*FAIL)/;
 print "Count=$count\n";

outputs

これの出力は

    aaab
    aaab
    Count=2

Once the 'aaab' at the start of the string has matched, and the (*SKIP) executed, the next starting point will be where the cursor was when the (*SKIP) was executed.

いったん文字列の最初の 'aaab' がマッチングして、(*SKIP) が実行されると、 次の開始位置は (*SKIP) が実行されたときのカーソルがいた位置になります。

(*MARK:NAME) (*:NAME)

This zero-width pattern can be used to mark the point reached in a string when a certain part of the pattern has been successfully matched. This mark may be given a name. A later (*SKIP) pattern will then skip forward to that point if backtracked into on failure. Any number of (*MARK) patterns are allowed, and the NAME portion may be duplicated.

このゼロ幅のマッチングはパターン内の特定の箇所がマッチングに成功したときに、 文字列の中で達した位置を記録するために使われます。 このマークには名前をつけることもできます。 後者の (*SKIP) パターンは失敗時でバックトラックしたときにその箇所まで スキップします。 (*MARK) パターンはいくつでも使うことができて、NAME 部分は 重複することもあります。

In addition to interacting with the (*SKIP) pattern, (*MARK:NAME) can be used to "label" a pattern branch, so that after matching, the program can determine which branches of the pattern were involved in the match.

(*SKIP) パターンとの相互動作に加えて、(*MARK:NAME) はパターン分岐の 「ラベル」としても使うことができます; このためマッチングの後で、プログラムは そのマッチングにおいてパターンのどの分岐が使われたのかを知ることができます。

When a match is successful, the $REGMARK variable will be set to the name of the most recently executed (*MARK:NAME) that was involved in the match.

マッチングの成功時に、$REGMARK 変数はマッチングの中で一番最近に 実行された (*MARK:NAME) の名前を設定します。

This can be used to determine which branch of a pattern was matched without using a separate capture group for each branch, which in turn can result in a performance improvement, as perl cannot optimize /(?:(x)|(y)|(z))/ as efficiently as something like /(?:x(*MARK:x)|y(*MARK:y)|z(*MARK:z))/.

これは書く分岐で別々の捕捉グループを使うことなしにパターンのどの分岐が マッチングしたのかを知るために使うことができます; これは perl は /(?:(x)|(y)|(z))//(?:x(*MARK:x)|y(*MARK:y)|z(*MARK:z))/ 程度に 効率的には最適化できないためパフォーマンスの向上をもたらします。

When a match has failed, and unless another verb has been involved in failing the match and has provided its own name to use, the $REGERROR variable will be set to the name of the most recently executed (*MARK:NAME).

マッチングが失敗して、そして他の記号がマッチングの失敗で行われずかつ名前を 持っているというのでなければ、$REGERROR 変数には一番最近に実行された (*MARK:NAME) の名前が設定されます。

See "(*SKIP)" for more details.

詳細は "(*SKIP)" を参照してください。

As a shortcut (*MARK:NAME) can be written (*:NAME).

(*MARK:NAME) の短縮形として (*:NAME) とも記述できます。

(*THEN) (*THEN:NAME)

This is similar to the "cut group" operator :: from Raku. Like (*PRUNE), this verb always matches, and when backtracked into on failure, it causes the regex engine to try the next alternation in the innermost enclosing group (capturing or otherwise) that has alternations. The two branches of a (?(condition)yes-pattern|no-pattern) do not count as an alternation, as far as (*THEN) is concerned.

これは Raku の "cut group" 演算子 :: と似ています。 (*PRUNE) のように、この記号は常にマッチングし、そして失敗で バックトラックした時に正規表現エンジンに、代替のある一番内側で閉じている グループ(キャプチャでもそうでなくとも)で次の代替を試みるようにさせます。 (*THEN) が有効である限り、 (?(condition)yes-pattern|no-pattern) の二つの枝は代替とは 扱われません。

Its name comes from the observation that this operation combined with the alternation operator ("|") can be used to create what is essentially a pattern-based if/then/else block:

この名前は代替演算子 ("|") と連結されたこの演算子で本質的にパターンベースの if/then/else ブロックとなるものを作るために使うことが できることからきています:

  ( COND (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ )

Note that if this operator is used and NOT inside of an alternation then it acts exactly like the (*PRUNE) operator.

この演算子が使われていてそしてそれが代替の内側ではなければ これはちょうど (*PRUNE) 演算子のように動作します。

  / A (*PRUNE) B /

is the same as

は次と同じです

  / A (*THEN) B /

but

しかし

  / ( A (*THEN) B | C ) /

is not the same as

は次と同じではありません

  / ( A (*PRUNE) B | C ) /

as after matching the A but failing on the B the (*THEN) verb will backtrack and try C; but the (*PRUNE) verb will simply fail.

A にマッチングしたけれど B に失敗した後 (*THEN) 記号は バックトラックして C を試みます; しかし (*PRUNE) 記号であれば 単純に失敗します。

(*COMMIT) (*COMMIT:arg)

This is the Raku "commit pattern" <commit> or :::. It's a zero-width pattern similar to (*SKIP), except that when backtracked into on failure it causes the match to fail outright. No further attempts to find a valid match by advancing the start pointer will occur again. For example,

これは Raku の"コミットパターン" <commit> または ::: です。 これは (*SKIP) と似たゼロ幅のパターンですが、失敗でバックトラックした 際にマッチングがすぐに失敗する点で異なります。 それ以降で開始位置を進めて有効なマッチングを探す試行は行われません。 例えば、

 'aaabaaab' =~ /a+b?(*COMMIT)(?{print "$&\n"; $count++})(*FAIL)/;
 print "Count=$count\n";

outputs

これの出力は

    aaab
    Count=1

In other words, once the (*COMMIT) has been entered, and if the pattern does not match, the regex engine will not try any further matching on the rest of the string.

言い換えると、いったん (*COMMIT) に入った後に、そのパターンが マッチングしなかったのなら、正規表現エンジンは文字列の残りに対して それ以上のマッチングを試みません。

(*FAIL) (*F) (*FAIL:arg)

This pattern matches nothing and always fails. It can be used to force the engine to backtrack. It is equivalent to (?!), but easier to read. In fact, (?!) gets optimised into (*FAIL) internally. You can provide an argument so that if the match fails because of this FAIL directive the argument can be obtained from $REGERROR.

このパターンは何にもマッチングせず常に失敗します。 これはエンジンを強制的にバックトラックさせるために使えます。 これは (?!) と等価ですが、より読みやすくなっています。 実際、(?!) は内部的には (*FAIL) に最適化されます。 この FAIL 指示子によってマッチングが失敗したときに $REGERROR から得られる、引数を指定できます。

It is probably useful only when combined with (?{}) or (??{}).

これはおそらく (?{}) または (??{}) と組み合わせた時にだけ 役に立つでしょう。

(*ACCEPT) (*ACCEPT:arg)

This pattern matches nothing and causes the end of successful matching at the point at which the (*ACCEPT) pattern was encountered, regardless of whether there is actually more to match in the string. When inside of a nested pattern, such as recursion, or in a subpattern dynamically generated via (??{}), only the innermost pattern is ended immediately.

このパターンマッチングは何もせず (*ACCEPT) パターンと遭遇した場所で 文字列の中で実際にもっとマッチングするものがあるかどうかにかかわらず 成功のマッチングを終了させます。 再帰、または (??{}) といったネストしたパターンの内側では、一番内側の パターンのみがすぐに終了します。

If the (*ACCEPT) is inside of capturing groups then the groups are marked as ended at the point at which the (*ACCEPT) was encountered. For instance:

(*ACCEPT) が捕捉グループの内側で使われた場合捕捉グループは (*ACCEPT) と遭遇した位置で終了とマークされます。 例えば:

  'AB' =~ /(A (A|B(*ACCEPT)|C) D)(E)/x;

will match, and $1 will be AB and $2 will be "B", $3 will not be set. If another branch in the inner parentheses was matched, such as in the string 'ACDE', then the "D" and "E" would have to be matched as well.

はマッチングし、$1AB になり、$2"B" に、そして $3 は設定されません。 'ACDE' のようにかっこの内側で他の分岐がマッチングしたのなら、 "D""E" もマッチングします。

You can provide an argument, which will be available in the var $REGMARK after the match completes.

マッチングが成功した後に $REGMARK 変数で利用可能な引数を指定できます。

Warning on \1 Instead of $1

($1 ではなく \1 だったときの警告)

Some people get too used to writing things like:

次のように書くことになれている人も中にはいるでしょう:

    $pattern =~ s/(\W)/\\\1/g;

This is grandfathered (for \1 to \9) for the RHS of a substitute to avoid shocking the sed addicts, but it's a dirty habit to get into. That's because in PerlThink, the righthand side of an s/// is a double-quoted string. \1 in the usual double-quoted string means a control-A. The customary Unix meaning of \1 is kludged in for s///. However, if you get into the habit of doing that, you get yourself into trouble if you then add an /e modifier.

(\1 から \9 については) sed 中毒な人をびっくりさせないための RHS 置換の 祖先ですが、しかしこれは汚らしい癖です。 Perl においては、s/// の右側はダブルクォートされた文字列と 考えられるためです。 通常のダブルクォートされた文字列の中では \1 は control-A を意味します。 \1 の Unix での習慣的な意味は s/// だけのその場しのぎです。 しかしながら、この癖に漬かっていると /e 修飾子を使ったときに トラブルとなるでしょう。

    s/(\d+)/ \1 + 1 /eg;            # causes warning under -w

Or if you try to do

または次のようにするかもしれません

    s/(\d+)/\1000/;

You can't disambiguate that by saying \{1}000, whereas you can fix it with ${1}000. The operation of interpolation should not be confused with the operation of matching a backreference. Certainly they mean two different things on the left side of the s///.

これを解消するために \{1}000 としないでください; ここでは ${1}000 とするべきです。 埋め込みの処理は後方参照にマッチングさせる操作より混乱は少ないでしょう。 特に s/// 側では2つの異なった意味になります。

ゼロ幅の部分文字列にマッチングするパターンの繰り返し

WARNING: Difficult material (and prose) ahead. This section needs a rewrite.

警告: この先には難しい(そして無味乾燥な)内容があります。 このセクションは書き直す必要があるでしょう。

Regular expressions provide a terse and powerful programming language. As with most other power tools, power comes together with the ability to wreak havoc.

正規表現は簡潔でパワフルなプログラミング言語を提供します。 他の多くの強力なツールとともに、力は破壊の源にもなります。

A common abuse of this power stems from the ability to make infinite loops using regular expressions, with something as innocuous as:

この力のよくある乱用は無害な何かとともに、正規表現使った 無限ループとなります。

    'foo' =~ m{ ( o? )* }x;

The o? matches at the beginning of "foo", and since the position in the string is not moved by the match, o? would match again and again because of the "*" quantifier. Another common way to create a similar cycle is with the looping modifier /g:

o? は "foo" の始まりにマッチングし、文字列中での位置はこの マッチングでは動かないので、o?"*" 量指定子によって何回も マッチングします。 同じような繰り返しを作るもう一つのよくある形として /g 修飾子を使った ループがあります:

    @matches = ( 'foo' =~ m{ o? }xg );

or

または

    print "match: <$&>\n" while 'foo' =~ m{ o? }xg;

or the loop implied by split().

または split() による暗黙のループ。

However, long experience has shown that many programming tasks may be significantly simplified by using repeated subexpressions that may match zero-length substrings. Here's a simple example being:

しかしながら、長きにわたる経験からいくつかのプログラミングタスクは ゼロ幅の部分文字列に対するマッチングを行う部分式の繰り返しで大幅に 単純にできることがわかりました。 簡単な例を挙げてみます:

    @chars = split //, $string;           # // is not magic in split
    ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /

Thus Perl allows such constructs, by forcefully breaking the infinite loop. The rules for this are different for lower-level loops given by the greedy quantifiers *+{}, and for higher-level ones like the /g modifier or split() operator.

このように Perl は 強制的に無限ループを砕く ことによってこういった構築を 可能にしています。 このためのルールは貪欲な量指定子 *+{} によって与えられる 低レベルなループとも、/g 修飾子や split() 演算子による 高レベルなループとも異なります。

The lower-level loops are interrupted (that is, the loop is broken) when Perl detects that a repeated expression matched a zero-length substring. Thus

低レベルなループは Perl がゼロ幅の部分文字列に対してマッチングする式が 繰り返されたことを検出すると 中断 されます (つまり、ループは壊されます)。 従って

   m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;

is made equivalent to

は次と等価にされます

   m{ (?: NON_ZERO_LENGTH )* (?: ZERO_LENGTH )? }x;

For example, this program

例えば、以下のプログラムは

   #!perl -l
   "aaaaab" =~ /
     (?:
        a                 # non-zero
        |                 # or
       (?{print "hello"}) # print hello whenever this
                          #    branch is tried
       (?=(b))            # zero-width assertion
     )*  # any number of times
    /x;
   print $&;
   print $1;

prints

以下を表示します

   hello
   aaaaa
   b

Notice that "hello" is only printed once, as when Perl sees that the sixth iteration of the outermost (?:)* matches a zero-length string, it stops the "*".

"hello" は一度だけ表示されることに注目して下さい; Perl は 一番外側の (?:)* の 6 回目の繰り返しがゼロ長文字列にマッチングするのを 見るので、"*" を止めます。

The higher-level loops preserve an additional state between iterations: whether the last match was zero-length. To break the loop, the following match after a zero-length match is prohibited to have a length of zero. This prohibition interacts with backtracking (see "Backtracking"), and so the second best match is chosen if the best match is of zero length.

高レベルのループは各繰り返しの間に最後のマッチングがゼロ幅だったかどうかを 追加で保持しています。 ループを終えるために、ゼロ幅のマッチングの後のマッチングはゼロ幅と なることを拒否します。 この禁則処理はバックトラックと相互に動作し("Backtracking" 参照)、そして ベストな マッチングがゼロ幅だったのなら 2 番目にベストな マッチングが選択されます。

For example:

例:

    $_ = 'bar';
    s/\w??/<$&>/g;

results in <><b><><a><><r><>. At each position of the string the best match given by non-greedy ?? is the zero-length match, and the second best match is what is matched by \w. Thus zero-length matches alternate with one-character-long matches.

これは <><b><><a><><r><> となります。 文字列の各位置に於いて、貪欲でない ?? によって得られるベストな マッチングはゼロ幅のマッチングです、 そして 2 番目にベストなマッチングは \w によってマッチングするものです。 従ってゼロ幅のマッチングは 1 文字幅のマッチングの代替となります。

Similarly, for repeated m/()/g the second-best match is the match at the position one notch further in the string.

同じように、m/()/g の繰り返しでは文字列中の境界一つ遠い位置に 2 番目に ベストなマッチングがマッチングします。

The additional state of being matched with zero-length is associated with the matched string, and is reset by each assignment to pos(). Zero-length matches at the end of the previous match are ignored during split.

ゼロ幅にマッチングしている という追加の状態はマッチングした文字列に 関連づけられていて、pos() に対する割り当てによってリセットされます。 前のマッチングの終端でのゼロ幅のマッチングは split の間は無視されます。

RE の欠片の結合

Each of the elementary pieces of regular expressions which were described before (such as ab or \Z) could match at most one substring at the given position of the input string. However, in a typical regular expression these elementary pieces are combined into more complicated patterns using combining operators ST, S|T, S* etc. (in these examples "S" and "T" are regular subexpressions).

これまでに説明された (ab\Z といった) 正規表現の基本的な欠片 それぞれは、入力文字列上の与えられた位置で多くとも1つの部分文字列に マッチングします。 しかしながら、典型的な正規表現ではこれらの基本的な欠片は結合演算 STS|TS* 等(ここで "S""T" は正規表現の部分式)を使って より複雑なパターンへと合成することができます。

Such combinations can include alternatives, leading to a problem of choice: if we match a regular expression a|ab against "abc", will it match substring "a" or "ab"? One way to describe which substring is actually matched is the concept of backtracking (see "Backtracking"). However, this description is too low-level and makes you think in terms of a particular implementation.

このような合成には選択の問題を導くために代替を含めることができます: 正規表現 a|ab"abc" に対してマッチングさせようとしたとき、これは "a""ab" のどちらにマッチングするのか? 実際にどちらがマッチングするのかを説明する1つの方法として、 バックトラッキングのコンセプトがあります("Backtracking" 参照)。 しかしながら、この説明は低レベルすぎて特定の実装を考えなければなりません。

Another description starts with notions of "better"/"worse". All the substrings which may be matched by the given regular expression can be sorted from the "best" match to the "worst" match, and it is the "best" match which is chosen. This substitutes the question of "what is chosen?" by the question of "which matches are better, and which are worse?".

もう一つの説明は"より良い"/"より悪い"の考え方で始めます。 与えられた正規表現にマッチングするすべての部分文字列は「最良の」 マッチングから「最悪の」マッチングへとソートすることができます; そして 「最良の」マッチングが選択されます。 これは「どれが選ばれるのか?」という問いかけを「どのマッチングがより良くて、 それがより悪いのか?」という問いかけに置き換えることができます。

Again, for elementary pieces there is no such question, since at most one match at a given position is possible. This section describes the notion of better/worse for combining operators. In the description below "S" and "T" are regular subexpressions.

そして、基本的な要素ではそういった問いかけはありません; なぜならこれらは与えられた位置で可能なマッチングは多くとも1つだからです。 このセクションでは結合演算のより良い/より悪いの考え方で説明していきます。 以下の説明では "S" 及び "T" は正規表現の部分式です。

ST

Consider two possible matches, AB and A'B', "A" and A' are substrings which can be matched by "S", "B" and B' are substrings which can be matched by "T".

2つの可能なマッチング、AB 及び A'B' を考えます; ここで "A" 及び A'"S" にマッチングする部分文字列、 そして "B" 及び B'"T" にマッチングする部分文字列とします。

If "A" is a better match for "S" than A', AB is a better match than A'B'.

もし "A""S" に対して A' よりも良いマッチングであれば、 ABA'B' よりも良いマッチングです。

If "A" and A' coincide: AB is a better match than AB' if "B" is a better match for "T" than B'.

もし "A"A' が同じであれば: "B""T" に対して B' よりも 良いマッチングであれば ABAB' よりも良いマッチングです。

S|T

When "S" can match, it is a better match than when only "T" can match.

"S" がマッチングできる時は "T" のみがマッチングするよりも良い マッチングです。

Ordering of two matches for "S" is the same as for "S". Similar for two matches for "T".

"S" に対する2つのマッチングの順序は "S" と同じです。 "T" に対する2つのマッチングも同様です。

S{REPEAT_COUNT}

Matches as SSS...S (repeated as many times as necessary).

SSS...S (必要なだけ繰り返し)としてマッチングします。

S{min,max}

Matches as S{max}|S{max-1}|...|S{min+1}|S{min}.

S{max}|S{max-1}|...|S{min+1}|S{min} としてマッチングします。

S{min,max}?

Matches as S{min}|S{min+1}|...|S{max-1}|S{max}.

S{min}|S{min+1}|...|S{max-1}|S{max} としてマッチングします。

S?, S*, S+

Same as S{0,1}, S{0,BIG_NUMBER}, S{1,BIG_NUMBER} respectively.

それぞれ S{0,1}, S{0,BIG_NUMBER}, S{1,BIG_NUMBER} と同じです。

S??, S*?, S+?

Same as S{0,1}?, S{0,BIG_NUMBER}?, S{1,BIG_NUMBER}? respectively.

それぞれ S{0,1}?, S{0,BIG_NUMBER}?, S{1,BIG_NUMBER}? と同じです。

(?>S)

Matches the best match for "S" and only that.

"S" の最良のみマッチングします。

(?=S), (?<=S)

Only the best match for "S" is considered. (This is important only if "S" has capturing parentheses, and backreferences are used somewhere else in the whole regular expression.)

"S" の最良のマッチングのみが考慮されます。 (これは "S" がキャプチャかっこを持っていて、そして正規表現全体の どこかで後方参照が使われている時のみ重要です.)

(?!S), (?<!S)

For this grouping operator there is no need to describe the ordering, since only whether or not "S" can match is important.

このグループ演算子では、"S" がマッチングできるかどうかのみが重要なので、 順序についての説明は必要ありません。

(??{ EXPR }), (?PARNO)

The ordering is the same as for the regular expression which is the result of EXPR, or the pattern contained by capture group PARNO.

順序は EXPR の結果の正規表現、または捕捉グループ PARNO に含まれている パターンと同じです。

(?(condition)yes-pattern|no-pattern)

Recall that which of yes-pattern or no-pattern actually matches is already determined. The ordering of the matches is the same as for the chosen subexpression.

既に決定している yes-pattern または no-pattern を実際に マッチングさせます。 マッチングの順序は選択された部分式と同じです。

The above recipes describe the ordering of matches at a given position. One more rule is needed to understand how a match is determined for the whole regular expression: a match at an earlier position is always better than a match at a later position.

ここにあげたレシピは与えられた位置でのマッチングの順序について 説明しています。 正規表現全体でマッチングがどのように決定されるかを理解するためには もう少しルールが必要です: より若い位置でのマッチングは後ろの方でのマッチングよりもより良いです。

カスタム RE エンジンの作成

As of Perl 5.10.0, one can create custom regular expression engines. This is not for the faint of heart, as they have to plug in at the C level. See perlreapi for more details.

Perl 5.10.0 から、誰でもカスタム正規表現エンジンを作成できます。 これは気弱な人向けではありません; C レベルでプラグインする必要があるからです。 さらなる詳細については perlreapi を参照して下さい。

As an alternative, overloaded constants (see overload) provide a simple way to extend the functionality of the RE engine, by substituting one pattern for another.

代替案として、オーバーロードされた定数(overload 参照)は あるパターンを別のパターンに置き換えることで、RE エンジンの機能を 拡張する簡単な方法を提供します。

Suppose that we want to enable a new RE escape-sequence \Y| which matches at a boundary between whitespace characters and non-whitespace characters. Note that (?=\S)(?<!\S)|(?!\S)(?<=\S) matches exactly at these positions, so we want to have each \Y| in the place of the more complicated version. We can create a module customre to do this:

新しい正規表現エスケープシーケンス、空白文字と非空白文字との 境界にマッチングする \Y| を作ってみることにします。 この位置には実際には (?=\S)(?<!\S)|(?!\S)(?<=\S) がマッチングするので、 この複雑なバージョンを \Y| で置き換えたいとします。 このために customre モジュールを作ります:

    package customre;
    use overload;

    sub import {
      shift;
      die "No argument to customre::import allowed" if @_;
      overload::constant 'qr' => \&convert;
    }

    sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}

    # We must also take care of not escaping the legitimate \\Y|
    # sequence, hence the presence of '\\' in the conversion rules.
    my %rules = ( '\\' => '\\\\',
                  'Y|' => qr/(?=\S)(?<!\S)|(?!\S)(?<=\S)/ );
    sub convert {
      my $re = shift;
      $re =~ s{
                \\ ( \\ | Y . )
              }
              { $rules{$1} or invalid($re,$1) }sgex;
      return $re;
    }

Now use customre enables the new escape in constant regular expressions, i.e., those without any runtime variable interpolations. As documented in overload, this conversion will work only over literal parts of regular expressions. For \Y|$re\Y| the variable part of this regular expression needs to be converted explicitly (but only if the special meaning of \Y| should be enabled inside $re):

これで use customre することで正規表現定数の中で新しいエスケープを 使うことが出来ます; すなわち、これには何の実行時変数の埋め込みもいりません。 overload に書かれているように、この変換は正規表現のリテラル部分にのみ 動作します。 \Y|$re\Y| であればこの正規表現の変数部分は明示的に変換する 必要があります(とはいえ $re の中でも \Y| を有効にしたい時のみ)。

    use customre;
    $re = <>;
    chomp $re;
    $re = customre::convert $re;
    /\Y|$re\Y|/;

組み込みコードの実行頻度

The exact rules for how often (?{}) and (??{}) are executed in a pattern are unspecified, and this is even more true of (*{}). In the case of a successful match you can assume that they DWIM and will be executed in left to right order the appropriate number of times in the accepting path of the pattern as would any other meta-pattern. How non- accepting pathways and match failures affect the number of times a pattern is executed is specifically unspecified and may vary depending on what optimizations can be applied to the pattern and is likely to change from version to version.

パターン中で (?{})(??{}) がどれくらいの頻度で実行されるかの 正確な規則は未規定で、これは (*{}) ですら真です。 マッチングが成功した場合、それらは DWIM を行い、 他のメタパターンと同様、 パターンの受け入れられたパスの中で左から右の順序で適切な回数 実行されることを仮定できます。 受け入れられなかったパスとマッチングの失敗がどれくらいパターンの実行回数に 影響を与えるかは明確に非規定で、 パターンにどの最適化が適用できるかに依存し、バージョン毎に 変わる可能性が高いです。

For instance in

例えば:

  "aaabcdeeeee"=~/a(?{print "a"})b(?{print "b"})cde/;

the exact number of times "a" or "b" are printed out is unspecified for failure, but you may assume they will be printed at least once during a successful match, additionally you may assume that if "b" is printed, it will be preceded by at least one "a".

失敗時に "a" や "b" が何回表示されるかは未規定ですが、 マッチングに成功したときに少なくとも 1 回表示されることは仮定でき、 さらに "b" が表示されるとき、その前には少なくとも 1 回 "a" が 表示されることも仮定できます。

In the case of branching constructs like the following:

次のような分岐構文の場合:

  /a(b|(?{ print "a" }))c(?{ print "c" })/;

you can assume that the input "ac" will output "ac", and that "abc" will output only "c".

入力が "ac" なら出力は "ac"、入力が "abc" なら出力は "c" だけと仮定できます。

When embedded code is quantified, successful matches will call the code once for each matched iteration of the quantifier. For example:

組み込みコードが量指定された場合、マッチングに成功すると 量指定子のそれぞれのマッチングした反復毎に 1 回コードを呼び出します。 例えば:

  "good" =~ /g(?:o(?{print "o"}))*d/;

will output "o" twice.

これは "o" を 2 回出力します。

For historical and consistency reasons the use of normal code blocks anywhere in a pattern will disable certain optimisations. As of 5.37.7 you can use an "optimistic" codeblock, (*{ ... }) as a replacement for (?{ ... }), if you do *not* wish to disable these optimisations. This may result in the code block being called less often than it might have been had they not been optimistic.

歴史的および一貫性の理由により、パターン中のどこかで通常の コードブロックを使うと、一部の最適化が無効化されます。 5.37.7 以降、これらの最適化が無効化されるのを望まない場合、 (?{ ... }) の代わりに「楽観的」コードブロックである (*{ ... }) を使えます。 これにより、楽観的でない場合より、コードブロックが呼び出される頻度が 少なくなるかもしれません。

PCRE/Python サポート

As of Perl 5.10.0, Perl supports several Python/PCRE-specific extensions to the regex syntax. While Perl programmers are encouraged to use the Perl-specific syntax, the following are also accepted:

Perl 5.10.0 時点では Perl は幾つかの Python/PCRE 的な正規表現構文拡張を サポートします。 Perl プログラマはこれらの Perl としての構文を推奨しますが、以下のものも 受理されます:

(?P<NAME>pattern)

Define a named capture group. Equivalent to (?<NAME>pattern).

名前付の捕捉グループの定義。 (?<NAME>pattern) と等価。

(?P=NAME)

Backreference to a named capture group. Equivalent to \g{NAME}.

名前付捕捉グループへの後方参照。 \g{NAME} と等価。

(?P>NAME)

Subroutine call to a named capture group. Equivalent to (?&NAME).

名前付き捕捉グループへの関数呼び出し。 (?&NAME) と等価。

バグ

There are a number of issues with regard to case-insensitive matching in Unicode rules. See "i" under "Modifiers" above.

Unicode ルールでの大文字小文字を無視したマッチングには多くの問題が あります。 上述の "Modifiers""i" を参照してください。

This document varies from difficult to understand to completely and utterly opaque. The wandering prose riddled with jargon is hard to fathom in several places.

この文書は、理解が困難なところから、完全かつ徹底的に不明瞭なところまで さまざまです。 jargon に満ちたとりとめのない散文は幾つかの箇所で理解するのに 難儀ではあるでしょう。

This document needs a rewrite that separates the tutorial content from the reference content.

この文書はリファレンス的な内容からチュートリアル的な内容を分離して 書き直す必要があります。

SEE ALSO

The syntax of patterns used in Perl pattern matching evolved from those supplied in the Bell Labs Research Unix 8th Edition (Version 8) regex routines. (The code is actually derived (distantly) from Henry Spencer's freely redistributable reimplementation of those V8 routines.)

Perl のパターンマッチングで使われる文法は、 the Bell Labs Research Unix 8th Edition (Version 8) 正規表現ルーチンで 提供されているものからの派生です。 (コードは実際には Henry Spencer の自由に再配布可能な V8 ルーチンの再実装から (遠く)派生しています)。

perlrequick.

perlretut.

"Regexp Quote-Like Operators" in perlop.

"Gory details of parsing quoted constructs" in perlop.

perlfaq6.

"pos" in perlfunc.

perllocale.

perlebcdic.

Mastering Regular Expressions by Jeffrey Friedl, published by O'Reilly and Associates.

O'Reilly and Associates から出版されている、Jeffrey Friedl による Mastering Regular Expressions (詳説 正規表現)