=encoding euc-jp =head1 NAME X X X =begin original perlre - Perl regular expressions =end original perlre - Perl の正規表現 =head1 DESCRIPTION =begin original This page describes the syntax of regular expressions in Perl. =end original このページでは Perl での正規表現の構文について説明します。 =begin original If you haven't used regular expressions before, a tutorial introduction is available in L. If you know just a little about them, a quick-start introduction is available in L. =end original もしこれまでに正規表現を使ったことがないなら、 L にチュートリアルがあります。 正規表現を少しだけ知っているなら、L に クイックスタートがあります。 =begin original Except for L 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 C, C, C and C<"??"> in L. =end original L 節を例外として、このページは、「パターン」とは何か、 それはどのような見た目のものか、基本的にどのようにして使われるか、といった 正規表現の基本に親しんでいることを仮定しています。 それらをどのように使うのかやそれに関する様々な例に 関しては、L にある C, C, C, C<"??"> の説明を参照して下さい。 =begin original New in v5.22, L|re/'strict' mode> applies stricter rules than otherwise when compiling regular expression patterns. It can find things that, while legal, may not be what you intended. =end original v5.22 から、L|re/'strict' mode> は、 正規表現パターンをコンパイルするときにその他よりもより厳しい規則を 適用します。 これは、正当ではあるけれども、意図していないかもしれないものを 見つけることができます。 =head2 The Basics X X X (基本) =begin original 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 C<=~> and C, listed in L; and the pattern will have been converted from an ordinary string by one of the operators in L, like so: =end original 正規表現とは、この文書と、この文書で参照される補助文書で記述されている、 特定の構文と意味を持つ文字列です。 この文字列は「パターン」と呼ばれます。 パターンは、「ターゲット」と呼ばれる他の文字列が、パターンで指定された 特性を持つ(または持たない)かどうかを判別するために使われます。 これをパターンに対するターゲット文字列の「マッチング」と呼びます。 通常、マッチングは、L にリストされている 二つの二項演算子 C<=~> および C の一つの、ターゲットを 最初のオペランドにし、パターンを 2 番目のオペランドにすることによって 行われます; そしてパターンは次のように、L の 演算子の一つによって通常の文字列から変換されています。 $foo =~ m/abc/ =begin original This evaluates to true if and only if the string in the variable C<$foo> contains somewhere in it, the sequence of characters "a", "b", then "c". (The C<=~ m>, or match operator, is described in L.) =end original これは、変数 C<$foo> 内の文字列のどこかに文字並び "a", "b", "c" が 含まれている場合にのみ真と評価されます。 (マッチング演算子 C<=~ m> は、L で 説明されています。) =begin original Patterns that aren't already stored in some variable must be delimitted, at both ends, by delimitter 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 delimitter 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 =end original 何らかの変数にまだ格納されていないパターンは、両端が区切り文字で 区切られている必要があります。 これらは上の例のようにスラッシュであることが多く、文書中で パターンを記述する一般的な方法はこれらのスラッシュです。 ほとんどの場合、区切り文字は前と後で同じ文字ですが、文字が鏡像のように 見える場合がいくつかあります; 次のように、開くのが開始区切り文字で、閉じるのが終了区切り文字です: $foo =~ m =begin original Most times, the pattern is evaluated in double-quotish context, but it is possible to choose delimiters to force single-quotish, like =end original ほとんどの場合、パターンはダブルクォート風コンテキストで評価されますが、 次のように区切り文字を選択してシングルクォート風を強制することもできます: $foo =~ m'abc' =begin original If the pattern contains its delimiter within it, that delimiter must be escaped. Prefixing it with a backslash (I, C<"/foo\/bar/">) serves this purpose. =end original パターン内に区切り文字が含まれている場合は、その区切り文字を エスケープする必要があります。 逆スラッシュを前置すると (例えば、C<"/foo\/bar/">)、この目的を 達成できます。 =begin original Any single character in a pattern matches that same character in the target string, unless the character is a I 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 C. =end original パターン中のすべての単一の文字は、その文字が個々でまたはこの文書で 説明されている特別な意味を持った I<メタ文字> である場合以外は、 ターゲット文字列内の同じ文字にマッチングします。 非メタ文字の並びは、前述の C で見たように、 ターゲット文字列の同じ並びにマッチングします。 =begin original Only a few characters (all of them being ASCII punctuation characters) are metacharacters. The most commonly used one is a dot C<".">, which normally matches almost any character (including a dot itself). =end original ほんのいくつかの文字 (全て ASCII の句読点文字) がメタ文字です。 もっとも一般的に使われるものはドット C<"."> で、これは通常 (ドット自身を含む) ほとんどの文字にマッチングします。 =begin original You can cause characters that normally function as metacharacters to be interpreted literally by prefixing them with a C<"\">, just like the pattern's delimiter must be escaped if it also occurs within the pattern. Thus, C<"\."> matches just a literal dot, C<"."> instead of its normal meaning. This means that the backslash is also a metacharacter, so C<"\\"> matches a single C<"\">. And a sequence that contains an escaped metacharacter matches the same sequence (but without the escape) in the target string. So, the pattern C would match any target string that contains the sequence C<"blur\fl">. =end original 文字は C<"\"> で前置されることで通常はメタ文字としての機能を持っている文字を リテラルとして処理させられるようになります; パターンの区切り文字がパターンの中に現れる場合は エスケープされなければならないのと同様です。 従って、C<"\."> は、通常の意味ではなく、 単にリテラルなドット C<"."> にマッチングするようになります。 つまり、逆スラッシュもメタ文字なので、 "\\" は単一の C<"\"> にマッチングするということです。 エスケープされたメタ文字を含む並びは、ターゲット文字列の中の 同じ並び(但しエスケープなし)にマッチングします。 それで、パターン C は 並び C<"blur\fl"> を含むターゲット文字列にマッチングします。 =begin original The metacharacter C<"|"> is used to match one thing or another. Thus =end original メタ文字 C<"|"> は二つのもののどちらかをマッチングするのに使われます。 従って: $foo =~ m/this|that/ =begin original is TRUE if and only if C<$foo> contains either the sequence C<"this"> or the sequence C<"that">. Like all metacharacters, prefixing the C<"|"> with a backslash makes it match the plain punctuation character; in its case, the VERTICAL LINE. =end original これは C<$foo> に並び C<"this"> または並び C<"that"> のどちらかが 含まれている場合にのみ真になります。 全てのメタ文字と同様、C<"|"> に逆スラッシュを前置すると普通の句読点文字、 この場合は VERTICAL LINE にマッチングします。 $foo =~ m/this\|that/ =begin original is TRUE if and only if C<$foo> contains the sequence C<"this|that">. =end original これは、C<$foo> に C<"this|that"> という並びを含んでいる場合にのみ 真になります。 =begin original You aren't limited to just a single C<"|">. =end original 単一の C<"|"> だけに制限されません。 $foo =~ m/fee|fie|foe|fum/ =begin original is TRUE if and only if C<$foo> contains any of those 4 sequences from the children's story "Jack and the Beanstalk". =end original これは、C<$foo> に童話「ジャックとまめの木」から取った 四つの並びのいずれがを含んでいる場合にのみ真になります。 =begin original As you can see, the C<"|"> binds less tightly than a sequence of ordinary characters. We can override this by using the grouping metacharacters, the parentheses C<"("> and C<")">. =end original ここで見られるように、C<"|"> は通常の文字の並びより弱く結びつけます。 これはグループ化メタ文字であるかっこ C<"("> と C<")"> を使って 上書きできます。 $foo =~ m/th(is|at) thing/ =begin original is TRUE if and only if C<$foo> contains either the sequence S> or the sequence S>. 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 L. =end original これは C<$foo> に並び S> または並び S> のいずれかが含まれている場合にのみ TRUE が返されます。 かっこで囲まれたパターンの部分と一致する文字列の部分は、通常、後でパターン、 置換、プログラムで使用するために個別に使用できます。 これは「捕捉」(capturing)と呼ばれ、複雑になる場合があります。 L を参照してください。 =begin original The first alternative includes everything from the last pattern delimiter (C<"(">, C<"(?:"> (described later), I. or the beginning of the pattern) up to the first C<"|">, and the last alternative contains everything from the last C<"|"> 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. =end original 最初の代替には最後のパターン区切り (C<"(">, C<"(?:"> (後述) など、または パターンの始まり)から最初の C<"|"> までのすべてが含まれ、 最後の代替には最後の C<"|"> から次の閉じパターン区切りまでが含まれます。 通常代替をかっこの中に入れるのは、その開始位置と終了位置が少しはわかりやすく なるようにです。 =begin original 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 C against C<"barefoot">, only the C<"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.) =end original 代替は左から右へと試されます、なので最初の代替がその完全な式で マッチングしたのならそれが選択されます。 これは代替は貪欲である必要はないということを意味します。 例えば: C<"barefoot"> に対して C をマッチングさせると、 最初の代替から試されるので、C<"foo"> の部分がマッチングし、 これは対象の文字列に対して成功でマッチングします。 (これは重要ではないでしょうが、かっこを使ってマッチングしたテキストを 捕捉しているときには重要でしょう。) =begin original 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 L. 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. =end original 接頭辞付き逆スラッシュは、メタ文字の特殊な意味を取り除くだけでなく、 一部の文字や数字をそれ自体と一致させないように変更し、 代わりに特殊な意味を持つようにします。 これらは「エスケープシーケンス」と呼ばれ、L で 説明されています。 現在 Perl にとって特殊な意味を持たない (文字や数字の) 逆スラッシュシーケンスは、警告が有効になっている場合に警告を発します; これらは将来使用するために予約されているためです。 =begin original One such sequence is C<\b>, which matches a boundary of some sort. C<\b{wb}> and a few others give specialized types of boundaries. (They are all described in detail starting at L.) Note that these don't match characters, but the zero-width spaces between characters. They are an example of a L. Consider again, =end original そのようなシーケンスのひとつは C<\b> です; これはある種の境界にマッチします。 C<\b{wb}> やその他のいくつかは特定の境界を与えます。 (これらはすべて L で詳細に 記述されています。) これらは文字ではなく、文字と文字の間のゼロ幅の スペースにマッチングすることに注意してください。 これらは L<ゼロ幅言明|/Assertions> の例です。 もう一度考えてみます: $foo =~ m/fee|fie|foe|fum/ =begin original It evaluates to TRUE if, besides those 4 words, any of the sequences "feed", "field", "Defoe", "fume", and many others are in C<$foo>. By judicious use of C<\b> (or better (because it is designed to handle natural language) C<\b{wb}>), we can make sure that only the Giant's words are matched: =end original これは、これら四つの単語以外に、"feed", "field", "Defoe", "fume", その他多くのシーケンスのいずれかが C<$foo> にある場合、TRUE と評価されます。 C<\b>(または(自然言語を処理するように設計されているため) より良い C<\b{wb}>)を慎重に使用することで、 確実に巨人の単語だけが一致するようにできます。 $foo =~ m/\b(fee|fie|foe|fum)\b/ $foo =~ m/\b{wb}(fee|fie|foe|fum)\b{wb}/ =begin original The final example shows that the characters C<"{"> and C<"}"> are metacharacters. =end original 最後の例は、文字 C<"{"> と C<"}"> がメタ文字であることを示しています。 =begin original 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 L, but the next three paragraphs briefly describe some of them. =end original エスケープシーケンスのもう一つの使用法は、文字通りに書くことができない (あるいは書きたくない)文字を指定することです。 これらについては L で詳しく説明していますが、 次の三つの段落でその一部を簡単に説明します。 =begin original Various control characters can be written in C language style: C<"\n"> matches a newline, C<"\t"> a tab, C<"\r"> a carriage return, C<"\f"> a form feed, I. =end original 様々な制御文字は C 言語形式で書くことができます: "\n" は改行にマッチングし、C<"\t"> はタブに、C<"\r"> は復帰に、 C<"\f"> はフォームフィードにといった具合にマッチングします。 =begin original More generally, C<\I>, where I is a string of three octal digits, matches the character whose native code point is I. 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 C<\o{...}> to specify any number of octal digits. =end original より一般的に、C<\I> (I は 3 桁の 8 進数字) は ネイティブな符号位置が I の文字にマッチングします。 正確に 3 桁以外の数字を使うと、簡単に困難に陥ります。 従って、常に 3 桁で使うか、Perl 5.14 以降なら、 任意の桁の 8 進数を使うために C<\o{...}> を使えます。 =begin original Similarly, C<\xI>, where I are hexadecimal digits, matches the character whose native ordinal is I. Again, not using exactly two digits is a recipe for disaster, but you can use C<\x{...}> to specify any number of hex digits. =end original 同じように、\xI (I は16進数字) はネイティブな数値で I に なる文字にマッチングします。 再び、正確に 2 桁以外の数字を使うのは災いの元ですが、 任意の桁の 16 進数を指定するために C<\x{...}> を使えます。 =begin original Besides being a metacharacter, the C<"."> 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 C<".">; there is a separate reference page about just these, L. =end original メタ文字であることに加えて、C<"."> は、特定の集合の任意の 1 文字に マッチングする「文字クラス」の例です。 この場合、集合ははほぼすべての可能な文字です。 Perlは C<"."> 以外にもいくつかの文字クラスを事前定義しています; これらについては、L という別のリファレンスページが あります。 =begin original 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 C<[]> 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 C<"["> character is another metacharacter. It doesn't match anything just by itelf; 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 C<"\[">. The matching C<"]"> 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 C<"[">, and matches its literal self: =end original 独自のカスタム文字クラスを定義するには、パターン内の適切な場所に、集合内に 必要なすべての文字のリストを配置します。 これを行うには、リストを C<[]> 大かっこ文字で囲みます。 これらは、正確にであれば「大かっこ文字クラス」と呼ばれますが、 「大かっこ」という単語が削除されることがよくあります。 (通常は、これを削除しても混乱は生じません。) これは、C<"["> 文字はもう一つのメタ文字であることを意味します。 これ自身だけでは何にもマッチングしません; Perl に対して、後に続くものが大かっこ文字クラスであることを 伝えるためにのみ使用されます。 リテラルの左大かっこにマッチさせたい場合は、C<"\["> のように エスケープする必要があります。 一致する C<"]"> もメタ文字です; ここでも何にもマッチしませんが、カスタムクラスの終わりを Perl に マークするだけです。 これは「時々メタ文字」の例です。 対応する C<"["> が存在しない場合はメタ文字ではなく、 リテラルにマッチングします。 print "]" =~ /]/; # prints 1 =begin original The list of characters within the character class gives the set of characters matched by the class. C<"[abc]"> matches a single "a" or "b" or "c". But if the first character after the C<"["> is C<"^">, the class matches any character not in the list. Within a list, the C<"-"> character specifies a range of characters, so that C represents all characters between "a" and "z", inclusive. If you want either C<"-"> or C<"]"> itself to be a member of a class, put it at the start of the list (possibly after a C<"^">), or escape it with a backslash. C<"-"> is also taken literally when it is at the end of the list, just before the closing C<"]">. (The following all specify the same class of three characters: C<[-az]>, C<[az-]>, and C<[a\-z]>. All are different from C<[a-z]>, which specifies a class containing twenty-six characters, even on EBCDIC-based character sets.) =end original 文字クラスの中の文字のリストは、そのクラスがマッチングする 文字の集合を表しています。 C<"[abc]"> は単一の "a" または "b" または "c" にマッチングします。. しかし、C<"["> の後の最初の文字が C<"^"> だったときには、その文字クラスは リストの中にない任意の文字にマッチングします。 リストの中では、文字 C<"-"> は文字の範囲を意味します; なので C は "a" と "z" を含めてそれらの間にあるすべての文字を表します。 文字クラスの要素として C<"-"> または C<"]"> 自身を使いたい時には、 リストの先頭に (あるいは C<"^"> の後に) 置くか、逆スラッシュを使って エスケープします。 C<"-"> はリストの終端、リストを閉じる C<"]"> の直前にあったときも リテラルとして扱われます。 (次の例はすべて同じ3文字からなる文字クラスです: C<[-az]>, C<[az-]>, C<[a\-z]>。 これらはすべて EBCDIC ベースの文字集合であっても26文字からなる文字集合 C<[a-z]> とは異なります。) =begin original There is lots more to bracketed character classes; full details are in L. =end original 大かっこ文字クラスにはもっと色々な要素があります; 完全な詳細は L にあります。 =head3 Metacharacters X X<\> X<^> X<.> X<$> X<|> X<(> X<()> X<[> X<[]> (メタ文字) =begin original L introduced some of the metacharacters. This section gives them all. Most of them have the same meaning as in the I command. =end original L ではメタ文字の一部を導入しました。 この節ではその全てを示します。 そのほとんどは I コマンドと同じ意味を持ちます。 =begin original Only the C<"\"> 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 C<"\">, they match their corresponding punctuation character. In some cases, their meaning varies depending on various pattern modifiers that alter the default behaviors. See L. =end original C<"\"> のみが常にメタ文字です。 その他は時々にだけメタ文字です。 次の表は、すべてのメタ文字の一覧、使用方法の概要、 メタ文字になるコンテキストを示しています。 これらのコンテキスト以外では、または C<"\"> で始まる場合は、 対応する句読点文字とマッチングします。 場合によっては、既定の動作を変更するさまざまなパターン修飾子によって 意味が異なります。 L を参照してください。 =begin original 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 =end original 目的 場所 \ 次の文字をエスケープ もう一つの \ で エスケープしない限り常に ^ 文字列(または /m が使われていれば行) の [] の中以外 先頭にマッチング ^ [] クラスの補集合 [] の先頭 . 改行以外の任意の 1 文字にマッチング [] の中以外 (/s の下では改行を含む) $ 文字列の末尾にマッチング [] の中以外、しかし (または文字列の最後の改行の前; スカラの変数展開を または /m が使われていれば改行の前) 意味する | 代替 [] の中以外 () グループ化 [] の中以外 [ 大かっこ文字クラスの開始 [] の中以外 ] 大かっこ文字クラスの終了 [] のみで先頭以外 * 前にある要素に 0 回以上マッチング [] の中以外 + 前にある要素に 1 回以上マッチング [] の中以外 ? 前にある要素に 0 回または 1 回マッチング [] の中以外 { 前にある要素がマッチングする回数を指定する [] の中以外 並びの開始 { 以下のいくつかのエスケープシーケンスで シーケンスの意味の修飾子の開始 } { で開始した並びの終わり - 範囲を示す [] の内部のみ =begin original Notice that most of the metacharacters lose their special meaning when they occur in a bracketed character class, except C<"^"> has a different meaning when it is at the beginning of such a class. And C<"-"> and C<"]"> are metacharacters only at restricted positions within bracketed character classes; while C<"}"> is a metacharacter only when closing a special construct started by C<"{">. =end original ほとんどのメタ文字は、かっこで囲まれた文字クラス内で出現すると 特殊な意味を失うことに注意してください; ただし、C<"^"> は、そのようなクラスの先頭では異なる意味を持ちます。 また、C<"-"> と C<"]"> は、かっこ弧で囲まれた文字クラス内の限定された 位置でだけメタ文字になります; 一方、C<"}"> は、C<"{"> によって開始された特殊な構造体を 閉じるときにのみメタ文字です。 =begin original In double-quotish context, as is usually the case, you need to be careful about C<"$"> and the non-metacharacter C<"@">. Those could interpolate variables, which may or may not be what you intended. =end original ダブルクォート風のコンテキストでは、通常の場合と同様、 C<"$"> とメタ文字でない C<"@"> に注意する必要があります。 これらは変数を補完することができますが、それは 意図したものである場合とない場合があります。 =begin original These rules were designed for compactness of expression, rather than legibility and maintainability. The Lx and Exx> pattern modifiers allow you to insert white space to improve readability. And use of S>> adds extra checking to catch some typos that might silently compile into something unintended. =end original これらの規則は、読みやすさや保守性ではなく、表現のコンパクトさを 考慮して設計されています。 Lx and Exx> パターン修飾子を使用すると、読みやすさを 向上させるために空白を挿入できます。 また、S>> を使用すると、 意図しないものに暗黙的にコンパイルされる可能性のあるタイプミスを 捕捉するための追加チェックが追加されます。 =begin original By default, the C<"^"> character is guaranteed to match only the beginning of the string, the C<"$"> 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 C<"^"> or C<"$">. You may, however, wish to treat a string as a multi-line buffer, such that the C<"^"> will match after any newline within the string (except if the newline is the last character in the string), and C<"$"> will match before any newline. At the cost of a little more overhead, you can do this by using the Lm>> modifier on the pattern match operator. (Older programs did this by setting C<$*>, but this option was removed in perl 5.10.) X<^> X<$> X =end original デフォルトでは、文字 C<"^"> は文字列の先頭にのみ、そして文字 C<"$"> は 末尾(または末尾の改行の前)にのみマッチングすることを保証し、そして Perl は 文字列が 1 行のみを含んでいるという仮定でいくつかの最適化を行います。 埋め込まれている改行文字は C<"^"> や C<"$"> とはマッチングしません。 しかし文字列には複数行が格納されていて、C<"^"> は任意の改行の後(但し 改行文字が文字列の最後の文字だった場合は除く)、そして C<"$"> は任意の改行の 前でマッチングさせたいこともあるでしょう。 小さなオーバーヘッドはありますが、これはパターンマッチングで Lm>> 修飾子を使うことで行うことができます。 (古いプログラムでは C<$*> を設定することでこれを行っていましたが これは perl 5.10 では削除されています。) X<^> X<$> X =begin original To simplify multi-line substitutions, the C<"."> character never matches a newline unless you use the Ls>|/s> modifier, which in effect tells Perl to pretend the string is a single line--even if it isn't. X<.> X =end original 複数行での利用を簡単にするために、文字 C<"."> は Ls>|/s> 修飾子を 使って Perl に文字列を 1 行として処理すると Perl に伝えない限り、 改行にはマッチングしません。 X<.> X =head2 Modifiers (修飾子) =head3 Overview (概要) =begin original 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 L and L. =end original マッチングのデフォルトの振る舞いは、様々な修飾子 (modifier) で 変更できます。 パターンの解釈に関連する修飾子は、直後に一覧にしています。 Perl がパターンを使う方法を変更する 修飾子は L 及び L に 説明されています。 =over 4 =item B> X X X X =begin original Treat the string being matched against as multiple lines. That is, change C<"^"> and C<"$"> 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. =end original 文字列を複数行としてマッチングするように扱います。 つまり、C<"^"> 及び C<"$"> は文字列の最初の行の先頭および最後の行の末尾に対する マッチングから、文字列中の各行の銭湯と末尾に対するマッチングへと 変更されます。 =item B> X X X X =begin original Treat the string as single line. That is, change C<"."> to match any character whatsoever, even a newline, which normally it would not match. =end original 文字列を 1 行として扱います。 つまり、C<"."> は任意の 1 文字、通常はマッチングしない改行でさえも マッチングするように変更されます。 =begin original Used together, as C, they let the C<"."> match any character whatsoever, while still allowing C<"^"> and C<"$"> to match, respectively, just after and just before newlines within the string. =end original C として共に使うと、C<"^"> 及び C<"$"> はそれぞれ 文字列中の改行の直前及び直後のマッチングでありつつ、C<"."> は任意の文字に マッチングするようになります。 =item B> X X X X =begin original Do case-insensitive pattern matching. For example, "A" will match "a" under C. =end original 大文字小文字を区別しないパターンマッチングを行います。 例えば、C の下では "A" は "a" にマッチングします。 =begin original 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 L. =end original ロケールマッチングルールが有効になっている場合、符号位置 255 以下の場合は 現在のロケールから取られ、より大きい符号位置では Unicode ルールから 取られます。 しかし、Unicode ルールと非 Unicode ルールの境界(番号255/256) を またぐマッチングは、ロケールが UTF-8 のものでない限り成功しません。 L を参照してください。 =begin original There are a number of Unicode characters that match a sequence of multiple characters under C. For example, C should match the sequence C. 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 =end original C の基で複数の文字の並びにマッチングする Unicode 文字はたくさんあります。 例えば、C は並び C にマッチングするべきです。 複数の文字がパターン中にあってグループ化で分割されている場合、または どれかの文字に量指定子が付いている場合、Perl は今のところこれを行えません。 従って =begin original "\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! =end original "\N{LATIN SMALL LIGATURE FI}" =~ /fi/i; # マッチング "\N{LATIN SMALL LIGATURE FI}" =~ /[fi][fi]/i; # マッチングしない! "\N{LATIN SMALL LIGATURE FI}" =~ /fi*/i; # マッチングしない! =begin original # 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! =end original # 次のものはマッチングしないし、もししたとしても $1 と $2 が何になるか # はっきりしない!! "\N{LATIN SMALL LIGATURE FI}" =~ /(f)(i)/i; # マッチングしない! =begin original 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 L, and L. =end original Perl は、明示的にマッピングについて言及されていない限り、 大かっこ文字クラスの複数の文字にはマッチングしません; そして文字クラスが否定された場合はそれらには全くマッチングしません; さもなければとても混乱することがあるからです。 L と L を参照して下さい。 =item B> and B> X (B> と B>) =begin original Extend your pattern's legibility by permitting whitespace and comments. Details in Lx and Exx> =end original 空白やコメントを許可してパターンを読みやすくするように拡張します。 詳細は Lx and Exx> にあります。 =item B> X

X X =begin original Preserve the string matched such that C<${^PREMATCH}>, C<${^MATCH}>, and C<${^POSTMATCH}> are available for use after matching. =end original C<${^PREMATCH}>, C<${^MATCH}>, C<${^POSTMATCH}> といったマッチングされた 文字列をマッチングの後も使えるように維持します。 =begin original In Perl 5.20 and higher this is ignored. Due to a new copy-on-write mechanism, C<${^PREMATCH}>, C<${^MATCH}>, and C<${^POSTMATCH}> will be available after the match regardless of the modifier. =end original Perl 5.20 以降ではこれは無視されます。 新しいコピーオンライト機構により、 C<${^PREMATCH}>, C<${^MATCH}>, and C<${^POSTMATCH}> はこの修飾子に関わらず マッチングの後も利用可能です。 =item B>, B>, B>, and B> X X X X (B>, B>, B>, B>) =begin original These modifiers, all new in 5.14, affect which character-set rules (Unicode, I.) are used, as described below in L. =end original 5.14 から導入されたこれらの新しい修飾子は、どの文字集合規則 (Unicode など) が使われるかに影響を与えます; L で後述します。 =item B> X X X X =begin original Prevent the grouping metacharacters C<()> from capturing. This modifier, new in 5.22, will stop C<$1>, C<$2>, I... from being filled in. =end original グループ化メタ文字 C<()> が捕捉しないようにします。 5.22 からのこの修飾子は、C<$1>, C<$2> などを埋めるのを止めます。 "hello" =~ /(hi|hello)/; # $1 is "hello" "hello" =~ /(hi|hello)/n; # $1 is undef =begin original This is equivalent to putting C at the beginning of every capturing group: =end original これは各捕捉グループの始めに C を置くのと等価です: "hello" =~ /(?:hi|hello)/; # $1 is undef =begin original C can be negated on a per-group basis. Alternatively, named captures may still be used. =end original C はグループ単位で否定できます。 その代わりに、名前付き捕捉はまだ使えます。 "hello" =~ /(?-n:(hi|hello))/n; # $1 is "hello" "hello" =~ /(?hi|hello)/n; # $1 is "hello", $+{greet} is # "hello" =item Other Modifiers (その他の修飾子) =begin original There are a number of flags that can be found at the end of regular expression constructs that are I generic regular expression flags, but apply to the operation being performed, like matching or substitution (C or C respectively). =end original 一般的な正規表現フラグ I<ではない> ですが、マッチングや置換 (それぞれ C や C) のような操作が実行される時に適用される 多くのフラグが正規表現構文の末尾に見つけられます。 =begin original Flags described further in L are: =end original L に さらに記述されているフラグは: c - keep the current position during repeated matching g - globally match the pattern repeatedly in the string =begin original Substitution-specific modifiers described in L are: =end original 置換専用の修飾子で L に記述されているのは: 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 =back =begin original Regular expression modifiers are usually written in documentation as I, "the C modifier", even though the delimiter in question might not really be a slash. The modifiers C may also be embedded within the regular expression itself using the C<(?...)> construct, see L below. =end original 正規表現修飾子は文書中では通常「C 修飾子」のように記述され、 これは区切りが実際にはスラッシュでなくてもそう記述されます。 また、C 修飾子は C<(?...)> 構築子を使って正規表現内に 埋め込まれることもあります; 後述する L を 参照してください。 =head3 Details on some modifiers (一部の修飾子の詳細) =begin original Some of the modifiers require more explanation than given in the L above. =end original 修飾子の一部は前述の L よりもさらなる説明が必要です。 =head4 C and C (C と C) =begin original A single C tells the regular expression parser to ignore most whitespace that is neither backslashed nor within a bracketed character class. You can use this to break up your regular expression into more readable parts. Also, the C<"#"> 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!) =end original 単一の C は、逆スラッシュでエスケープされたり大かっこ文字クラスの 中だったりしないほとんどの空白を無視するように正規表現パーサに伝えます。 これは正規表現を読みやすく部分に分割するために使えます。 また C<"#"> は、パターンの閉じ区切り文字まで、またはパターンが次の行に 続く場合は現在の行の末尾までのコメントを開始するメタ文字として扱われます。 従って、これは通常の Perl コードのコメントととても似ています。 (コメントの中の閉じ区切り文字は、逆スラッシュを前置した場合にのみ 含めることができます; 注意してください!) =begin original Use of C means that if you want real whitespace or C<"#"> characters in the pattern (outside a bracketed character class, which is unaffected by C), then you'll either have to escape them (using backslashes or C<\Q...\E>) or encode them using octal, hex, or C<\N{}> escapes. It is ineffective to try to continue a comment onto the next line by escaping the C<\n> with a backslash or C<\Q>. =end original C の使用はまた、(C の影響を受けない大かっこ文字クラス内以外で) パターン中に本当の空白や C<"#"> 文字を使いたい場合は、(逆スラッシュや C<\Q...\E> を使って) エスケープするか、8 進数、16 進数、C<\N{}> エスケープのいずれかで エンコードする必要があると言うことです。 C<\n> を逆スラッシュや C<\Q> でエスケープすることで コメントを次の行まで続けようとしても無効です。 =begin original You can use L to create a comment that ends earlier than the end of the current line, but C also can't contain the closing delimiter unless escaped with a backslash. =end original 現在の行の末尾より早く修了するコメントを作るために L が使えますが、やはり C は逆スラッシュで エスケープされない限り閉じ区切り文字を含むことはできません。 =begin original A common pitfall is to forget that C<"#"> characters begin a comment under C and are not matched literally. Just keep that in mind when trying to puzzle out why a particular C pattern isn't working as expected. =end original よくある落とし穴は、C<"#"> 文字は C の下ではコメントを始めるので、 文字通りにマッチしないことを忘れてしまうことです。 特定の C パターンが期待通りに動作しない理由を解明しようとするときには、 このことを念頭に置いてください。 =begin original Starting in Perl v5.26, if the modifier has a second C<"x"> within it, it does everything that a single C does, but additionally non-backslashed SPACE and TAB characters within bracketed character classes are also generally ignored, and hence can be added to make the classes more readable. =end original Perl v5.26 以降では、修飾子に二つ目の C<"x"> が含まれている場合、 一つの C が行うことはすべて行いますが、かっこで囲まれた 文字クラス内の逆スラッシュのない SPACE および TAB 文字も一般に無視されます; したがって、クラスをより読みやすくするためにこれらを追加することができます。 / [d-e g-i 3-7]/xx /[ ! @ " # $ % ^ & * () = ? <> ' ]/xx =begin original may be easier to grasp than the squashed equivalents =end original これは、圧縮された同等物よりも掴みやすいかもしれません: /[d-eg-i3-7]/ /[!@"#$%^&*()=?<>']/ =begin original Taken together, these features go a long way towards making Perl's regular expressions more readable. Here's an example: =end original まとめると、これらの機能は Perl の正規表現をより読みやすくするために 大きく役立ちます。 以下は例です: # Delete (most) C comments. $program =~ s { /\* # Match the opening delimiter. .*? # Match a minimal number of characters. \*/ # Match the closing delimiter. } []gsx; =begin original Note that anything inside a C<\Q...\E> stays unaffected by C. And note that C doesn't affect space interpretation within a single multi-character construct. For example in C<\x{...}>, regardless of the C modifier, there can be no spaces. Same for a L such as C<{3}> or C<{5,}>. Similarly, C<(?:...)> can't have a space between the C<"(">, C<"?">, and C<":">. Within any delimiters for such a construct, allowed spaces are not affected by C, and depend on the construct. For example, C<\x{...}> can't have spaces because hexadecimal numbers don't have spaces in them. But, Unicode properties can have spaces, so in C<\p{...}> there can be spaces that follow the Unicode rules, for which see L. X =end original C<\Q...\E> の内側のものは C の影響を受けないことに注意してください。 例えば、C<\x{...}> の内部では、C 修飾子に関わらず、スペースを 含むことはできません。 C<{3}> や C<{5,}> のような L<量指定子|/Quantifiers> も同様です。 また、C<(?:...)> も C<"(">, C<"?">, C<":"> の間にスペースを含むことはできません。 このような構文の区切り文字の中では、スペースが許されるかどうかは C に影響されず、構文自身に影響されます。 例えば、16 進数はスペースを含むことができないので C<\x{...}> はスペースを 含むことができません。 しかし、Unicode 特性はスペースを含むことができるので、 C<\p{...}> は Unicode の規則に従ってスペースを含むことができます; L を 参照してください。 X =begin original The set of characters that are deemed whitespace are those that Unicode calls "Pattern White Space", namely: =end original 空白と見なされる文字の集合は、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 =head4 Character set modifiers (文字集合修飾子) =begin original C, C, C, and C, available starting in 5.14, are called the character set modifiers; they affect the character set rules used for the regular expression. =end original 5.14 から利用可能な C, C, C, C は文字集合修飾子と呼ばれます; これらは正規表現で使われる文字集合規則に影響を与えます。 =begin original The C, C, and C 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. =end original C, C, C 修飾子はよく使うことはないだろうものなので、 これらについてあまり心配する必要はありません。 これらは Perl の内部仕様のために存在しているので、 複雑な正規表現データ構造は自動的に直列化されて、その後全てのニュアンスを 含めて正確に再構成されます。 =begin original The C 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. =end original 一方、C 修飾子は有用かもしれません。 この目的は、Unicode に関して考慮する必要がないように、コードを ほとんど ASCII データとして動作するようにすることです。 =begin original Briefly, C sets the character set to that of whatever Bocale is in effect at the time of the execution of the pattern match. =end original 簡単に言うと、C は、文字集合をパターンマッチングの実行時に有効な ロケール(Bocale)に設定します。 =begin original C sets the character set to Bnicode. =end original C は文字集合を Bnicode に設定します。 =begin original C also sets the character set to Unicode, BUT adds several restrictions for BSCII-safe matching. =end original C も文字コードを Unicode に設定しますが、 BSCII セーフなマッチングのためにいくつかの制限を加えます。 =begin original C is the old, problematic, pre-5.14 Befault character set behavior. Its only use is to force that old behavior. =end original C は古くて問題のある、5.14 以前のデフォルト(Befault)文字集合の 振る舞いです。 これは古い振る舞いを強制するためだけに使います。 =begin original 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 only it. =end original 任意のある瞬間において、これらの修飾子の内正確に一つだけが有効になります。 これにより、 それが実際に実行されるときにどの規則が有効かに関わらず、 Perl が元々コンパイルされた正規表現の振る舞いを保存できるようにします。 そしてそれがより大きな正規表現に展開された場合、元の規則だけが 適用され続けます。 =begin original The C and C 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, =end original C と C の修飾子は、様々なプラグマのスコープ内でコンパイルされた 正規表現で自動的に選択されます; 一般的にはこれらの修飾子を明示的に使うのではなく、これらのプラグマを 使うことを勧めます。 一例を挙げると、修飾子はパターンマッチングに対してのみ影響を与え、 置換には拡張されないことに注意してください; いっぽうプラグマを使うと、そのスコープ内の全ての適切な操作について 一貫した結果となります。 例えば: s/foo/\Ubar/il =begin original will match "foo" using the locale's rules for case-insensitive matching, but the C does not affect how the C<\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 C. This both implicitly adds the C, and applies locale rules to the C<\U>. The lesson is to C, and not C explicitly. =end original これは大文字小文字マッチングにロケールの規則を使って "foo" に マッチングしますが、C は C<\U> がどう処理を行うかに影響を与えません。 あなたはほぼ確実にこれら二つにロケールの規則を使うことを臨むはずです。 これをするためには、代わりに C のスコープ内で正規表現をコンパイルします。 これらは両方とも暗黙に C を追加し、C<\U> にロケールの規則を適用します。 ここで学ぶべきことは、C を使って、明示的に C を 使わないことです。 =begin original Similarly, it would be better to use C instead of, =end original 同様に、Unicode の規則にするには次のようにする代わりに C を使った方が良いです: s/foo/\Lbar/iu =begin original to get Unicode rules, as the C<\L> in the former (but not necessarily the latter) would also use Unicode rules. =end original 前者の C<\L> (しかし後者は必要ではないです) も Unicode の規則を 使うからです。 =begin original More detail on each of the modifiers follows. Most likely you don't need to know this detail for C, C, and C, and can skip ahead to La|/Ea (and Eaa)>. =end original それぞれの修飾子に関するさらなる詳細は後述します。 ほとんど確実にあなたは C, C, C の詳細を知る必要はなく、 La|/Ea (and Eaa)> まで読み飛ばせます。 =head4 /l =begin original means to use the current locale's rules (see L) when pattern matching. For example, C<\w> will match the "word" characters of that locale, and C<"/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 L. =end original これはパターンマッチングのときに現在のロケールの規則 (L 参照) を 使うことを意味します。 例えば、C<\w> はこのロケールの「単語」文字にマッチングし、 C<"/i"> の大文字小文字マッチングは、現在のロケールの大文字小文字畳み込み規則に 従ってマッチングします。 使われるロケールはパターンマッチングが実行される時点で有効なものです。 これはコンパイル時のロケールと同じではないかもしれませんし、 L の呼び出しが間に入ると、呼び出し毎に異なることもあります。 =begin original 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. =end original v5.20 より前では、Perl は複数バイトロケールに対応していませんでした。 v5.20 から、UTF-8 ロケールに対応しました。 他の複数バイトロケールに対応することはおそらくありません。 しかし、全てのロケールで、255 を越える符号位置を保持することができ、 これはどのロケールが有効であるかに関わらず常に Unicode として扱われます。 =begin original 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 C. For example, 0xFF (on ASCII platforms) does not caselessly match the character at 0x178, C, because 0xFF may not be C 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. =end original Unicode の規則の基では、255/256 の境界をまたぐ大文字小文字を無視した マッチングがいくつかあります。 Perl v5.20 以降での UTF-8 ロケールを除いて、 これらは C の基では認められません。 例えば、(ASCII プラットフォームで) 0xFF は 0x178, C と大文字小文字を無視した マッチングをしません; なぜなら 0xFF は現在のロケールでは C ではないかもしれず、Perl は このロケールでこの文字があるかどうかすら知る方法がなく、ましてや これがどの符号位置かを知る方法もないからです。 =begin original 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 (see L). =end original v5.20 以降の UTF-8 ロケールでは、 正規表現でのロケールと非ロケールの目に見える唯一の違いは 汚染だけのはずです (L 参照)。 =begin original This modifier may be specified to be the default by C, but see L. X =end original この修飾子は C によってデフォルトで設定されますが、 L を参照してください。 X =head4 /u =begin original 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, C<\w> will match any of the more than 100_000 word characters in Unicode. =end original これはパターンマッチングのときに Unicode の規則を使うことを意味します。 ASCII プラットフォームでは、これは符号位置 128 から 255 は Latin-1 (ISO-8859-1) という意味になります (これは Unicode と同じです)。 (さもなければ Perl はこれらの意味は未定義として扱います。) 従って、この修飾子の基では、ASCII プラットフォームは 事実上 Unicode プラットフォームになります; 従って、 例えば、C<\w> は Unicode の 100,000 以上の単語文字のどれにも マッチングします。 =begin original Unlike most locales, which are specific to a language and country pair, Unicode classifies all the characters that are letters I in the world as C<\w>. For example, your locale might not think that C 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 C<\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, C (U+09EA) looks very much like an C (U+0038). And, C<\d+>, may match strings of digits that are a mixture from different writing systems, creating a security issue. L can be used to sort this out. Or the C modifier can be used to force C<\d> to match just the ASCII 0 through 9. =end original 特定の言語と国に固有であるほとんどのロケールと異なり、 Unicode は世界の I<どこか> で字(letter)として扱われている全ての 文字(character)を C<\w> に分類します。 例えば、あなたのロケールは (あなたがたまたまアイスランド語を話さない限り) C を字として考えないかもしれません。 同様に、世界のどこかで数字である全ての文字は C<\d> にマッチングします; これは 10 ではなく 100 のマッチングの可能性があります。 さらにこれらの数字の一部は 10 の ASCII 数字と似ていますが、 異なる数字を意味するため、人間はその数字が実際と異なる量であると 簡単に考えてしまいます。 例えば、 C (U+09EA) は C (U+0038) に とてもよく似ています。 C<\d+> は、異なる記法から混ぜた数字の文字列にマッチングするので、 セキュリティ上の問題を作ります。 これを整理するために L が使われます。 あるいは C 修飾子は、C<\d> が単に ASCII の 0 から 9 に マッチングすることを強制するために使えます。 =begin original Also, under this modifier, case-insensitive matching works on the full set of Unicode characters. The C, for example matches the letters "k" and "K"; and C matches the sequence "ff", which, if you're not prepared, might make it look like a hexadecimal constant, presenting another potential security issue. See L for a detailed discussion of Unicode security issues. =end original また、この修飾子の基では、大文字小文字を無視したマッチングは Unicode の 完全な集合で動作します。 例えば C は "k" と "K" にマッチングします; C は、準備していなければ 16 進数定数のように 見えるかもしれない並び "ff" にマッチングし、もう一つの潜在的な セキュリティ問題になります。 Unicode のセキュリティ問題に関する詳細な議論については L を参照してください。 =begin original This modifier may be specified to be the default by C, C, or C> (or higher), but see L. X =end original この修飾子は C, C, C> (またはそれ以上) によってデフォルトに 設定されますが、L を 参照してください。 X =head4 /d =begin original This modifier means to use the "Default" native rules of the platform except when there is cause to use Unicode rules instead, as follows: =end original この修飾子は、以下のように Unicode の規則が使われる場合を除いて、 プラットフォームの「デフォルトの」(Default) ネイティブな規則を使うことを 意味します: =over 4 =item 1 =begin original the target string is encoded in UTF-8; or =end original ターゲット文字列が UTF-8 でエンコードされている; または =item 2 =begin original the pattern is encoded in UTF-8; or =end original パターンが UTF-8 でエンコードされている; または =item 3 =begin original the pattern explicitly mentions a code point that is above 255 (say by C<\x{100}>); or =end original パターンが、(C<\x{100}> のような形で)255 を超える符号位置に明示的に 言及している; または =item 4 =begin original the pattern uses a Unicode name (C<\N{...}>); or =end original パターンが Unicode 名 (C<\N{...}>) を使っている; または =item 5 =begin original the pattern uses a Unicode property (C<\p{...}> or C<\P{...}>); or =end original パターンが Unicode 特性 (C<\p{...}>) や C<\P{...}>) を使っている; または =item 6 =begin original the pattern uses a Unicode break (C<\b{...}> or C<\B{...}>); or =end original パターンがUnicode 単語境界 (C<\b{...}> または C<\B{...}>) を使っている; または =item 7 =begin original the pattern uses L> =end original パターンが L> を使っている =back =begin original Another mnemonic for this modifier is "Depends", as the rules actually used depend on various things, and as a result you can get unexpected results. See L. The Unicode Bug has become rather infamous, leading to yet another (printable) name for this modifier, "Dodgy". =end original この修飾子のもう一つの記憶法は「依存」(Depends)です; 規則は実際には 様々なことに依存していること、また結果として予想外の 結果になるかもしれないからです。 L を参照してください。 Unicode バグは、悪名高くなり、この修飾子のもう一つの(表示可能な) 名前 "Dodgy" を引き起こしています。 =begin original Unless the pattern or string are encoded in UTF-8, only ASCII characters can match positively. =end original パターンや文字列が UTF-8 でエンコードされていない限り、 ASCII 文字のみが肯定的にマッチングします。 =begin original Here are some examples of how that works on an ASCII platform: =end original 以下は ASCII プラットフォームでどのように動作するかの例です: $str = "\xDF"; # $str is not in UTF-8 format. $str =~ /^\w/; # No match, as $str isn't in UTF-8 format. $str .= "\x{0e0b}"; # Now $str is in UTF-8 format. $str =~ /^\w/; # Match! $str is now in UTF-8 format. chop $str; $str =~ /^\w/; # Still a match! $str remains in UTF-8 format. =begin original This modifier is automatically selected by default when none of the others are, so yet another name for it is "Default". =end original この修飾子は他のものが指定されなかった場合にデフォルトとして自動的に 洗濯されるので、これのもう一つの名前は "Default" です。 =begin original Because of the unexpected behaviors associated with this modifier, you probably should only explicitly use it to maintain weird backward compatibilities. =end original この修飾子に関する想定外の振る舞いにより、おそらくおかしな後方互換性を 維持するためだけにこれを明示的に使うべきでしょう。 =head4 /a (and /aa) (/a (と /aa)) =begin original This modifier stands for ASCII-restrict (or ASCII-safe). This modifier may be doubled-up to increase its effect. =end original この修飾子は ASCII 制限 (あるいは ASCII セーフ) を意味します。 この修飾子は、2 倍にすることで効果が増します。 =begin original When it appears singly, it causes the sequences C<\d>, C<\s>, C<\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 C, C<\d> always means precisely the digits C<"0"> to C<"9">; C<\s> means the five characters C<[ \f\n\r\t]>, and starting in Perl v5.18, the vertical tab; C<\w> means the 63 characters C<[A-Za-z0-9_]>; and likewise, all the Posix classes such as C<[[:print:]]> match only the appropriate ASCII-range characters. =end original これが単体で使われると、C<\d>, C<\s>, C<\w>, Posix 文字クラスは ASCII の範囲のみにマッチングするようになります。 従って、これらは 5.6 以前の、Unicode 以前の意味に戻します。 C の基では、C<\d> は常に正確に数字 C<"0"> から C<"9"> を意味します; C<\s> は C<[ \f\n\r\t]> の 5 文字、および Perl v5.18 から垂直タブ、 を意味します; C<\w> は C<[A-Za-z0-9_]> の 63 文字を意味します; 同様に、C<[[:print:]]> のような全ての Posix クラスは 適切な ASCII の範囲の文字にのみマッチングします。 =begin original 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. =end original この修飾子は、偶然 Unicode を使っている人々で、その複雑さと セキュリティの問題に関する重荷を背負いたくない人々にとっては有用です。 =begin original With C, one can write C<\d> with confidence that it will only match ASCII characters, and should the need arise to match beyond ASCII, you can instead use C<\p{Digit}> (or C<\p{Word}> for C<\w>). There are similar C<\p{...}> constructs that can match beyond ASCII both white space (see L), and Posix classes (see L). Thus, this modifier doesn't mean you can't use Unicode, it means that to get Unicode matching you must explicitly use a construct (C<\p{}>, C<\P{}>) that signals Unicode. =end original C を使うと、ASCII 文字だけにマッチングすることに自信を持って 書くことができ、ASCII を超えてマッチングする必要が発生したときには、 代わりに C<\p{Digit}> (または C<\w> として C<\p{Word}>) が使えます。 ASCII を超えたスペース (L を参照してください) と Posix クラス (L を 参照してください) の両方にマッチングする似たような C<\p{...}> 構文があります。 従って、この修飾子は Unicode が使えなくなるということではなく、 Unicode のマッチングには明示的に Unicode を意味する構文 (C<\p{}>, C<\P{}>) を使わないといけないということです。 =begin original As you would expect, this modifier causes, for example, C<\D> to mean the same thing as C<[^0-9]>; in fact, all non-ASCII characters match C<\D>, C<\S>, and C<\W>. C<\b> still means to match at the boundary between C<\w> and C<\W>, using the C definitions of them (similarly for C<\B>). =end original 予想できるとおり、 この修飾子は、例えば、C<\D> を C<[^0-9]> と 同じことにします; 実際、全ての非 ASCII 文字は C<\D>, C<\S>, C<\W> にマッチングします。 C<\b> はまだ C<\w> と C<\W> の境界にマッチングします; これらのために (C<\B> と同様) C の定義を使います。 =begin original Otherwise, C behaves like the C modifier, in that case-insensitive matching uses Unicode rules; for example, "k" will match the Unicode C<\N{KELVIN SIGN}> under C matching, and code points in the Latin1 range, above ASCII will have Unicode rules when it comes to case-insensitive matching. =end original さもなければ、C は C 修飾子のように振る舞います; 大文字小文字を無視したマッチングには Unicode の規則を使います; 例えば、"k" は C の基では C<\N{KELVIN SIGN}> にマッチングし、 ASCII の範囲を超える Latin1 の範囲の符号位置は、大文字小文字を無視した マッチングで使われる場合は Unicode の規則を使います。 =begin original To forbid ASCII/non-ASCII matches (like "k" with C<\N{KELVIN SIGN}>), specify the C<"a"> twice, for example C or C. (The first occurrence of C<"a"> restricts the C<\d>, I., and the second occurrence adds the C restrictions.) But, note that code points outside the ASCII range will use Unicode rules for C matching, so the modifier doesn't really restrict things to just ASCII; it just forbids the intermixing of ASCII and non-ASCII. =end original ("k" と C<\N{KELVIN SIGN}> のような) ASCII/非-ASCII マッチングを禁止するには、 C や C のように C<"a"> を 2 回指定します。 (最初の C<"a"> は C<\d> などを制限し、2 番目は C の制限を追加します。) しかし、 ASCII の範囲外の符号位置は C マッチングに Unicode 規則を 使うので、この修飾子は実際には単に ASCII に制限するものではないことに 注意してください; これは単に ASCII と非 ASCII を混ぜることを禁止します。 =begin original 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. =end original まとめると、この修飾子は全ての Unicode に対して曝されることを望んでいない アプリケーションに対する保護を提供します。 2 回指定することで追加の保護を提供します。 =begin original This modifier may be specified to be the default by C or C. If you do so, you may actually have occasion to use the C 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 C<"unicode_strings">, along with the C). Also see L. X X =end original この修飾子は C または C でデフォルトに 設定されます。 そうすると、もし完全な Unicode 規則を使いたい正規表現がある場合は、 C 修飾子を明示的に使う機会があるかもしれません (その場合でも、全てが C<"unicode_strings"> の基なら、 C と共にするのが最良です)。 L も参照してください。 X X =head4 Which character set modifier is in effect? (どの文字集合修飾子が有効?) =begin original 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 L 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. =end original ある正規表現のあるポイントでどの修飾子が有効かは、かなり複雑な相互作用に 依存します。 これらは、基本的にはあなたがこれらについて心配しなくて良いように 設計されています。 しかし、この節は詳細を記述します。 L で後述するとおり、正規表現の一部にだけ 適用する修飾子を明示的に指定することが可能です。 一番内側のものは常により外側のものより優先され、式全体に適用されるものは この節の残りで記述されるデフォルト設定より優先されます。 =begin original The Cfoo'|re/"'/flags' mode">> 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. =end original Cfoo'|re/"'/flags' mode">> プラグマは、 このスコープ内でコンパイルされる正規表現に対して(これらを含む) デフォルトの修飾子を設定するのに使えます。 このプラグマは、デフォルトを変更する後述するその他のプラグマに優先します。 =begin original Otherwise, C> sets the default modifier to C; and C>, or C> (or higher) set the default to C when not in the same scope as either C> or C>. (C> also sets the default to C, overriding any plain C.) Unlike the mechanisms mentioned above, these affect operations besides regular expressions pattern matching, and so give more consistent results with other operators, including using C<\U>, C<\l>, I. in substitution replacements. =end original さもなければ、C> はデフォルト修飾子を C に 設定します; そして、C> か C> (またはそれ以上) は、 同じスコープに C> や C> が なければ、デフォルトを C に設定します。 (C> はまた デフォルトを C に設定し、普通の C を上書きします。) 前述した機構と異なり、これらは正規表現パターンマッチング以外の操作に 影響するので、置換での C<\U>, C<\l> を使うことを含むその他の操作と より一貫性のある結果になります。 =begin original If none of the above apply, for backwards compatibility reasons, the C 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. =end original 前述のどれも適用されない場合、後方互換性のために、 C 修飾子がデフォルトで有効になります。 これは想定外の結果になることがあるので、 その他の規則集合が使われるように指定するのが最良です。 =head4 Character set modifier behavior prior to Perl 5.14 (Perl 5.14 より前の文字集合修飾子の振る舞い) =begin original Prior to 5.14, there were no explicit modifiers, but C was implied for regexes compiled within the scope of C, and C 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 C modifier, where Unicode rules would be used when inappropriate, and vice versa. C<\p{}> did not imply Unicode rules, and neither did all occurrences of C<\N{}>, until 5.12. =end original 5.14 より前では、明示的な修飾子はありませんが、 C のスコープ内でコンパイルされた正規表現に関しては C が仮定され、さもなければ C が仮定されます。 しかし、ある正規表現をより大きな正規表現に展開した場合、元のコンパイル時の 状況は、2 回目のコンパイル時点で有効なもので上書きされます。 C 演算子には、不適切なときに Unicode 規則が使われる、あるいはその逆の 多くの非一貫性(バグ)があります。 C<\p{}> および C<\N{}> は 5.12 まで Unicode 規則を仮定していません。 =head2 Regular Expressions (正規表現) =head3 Quantifiers (量指定子) =begin original 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: X X X<*> X<+> X X<{n}> X<{n,}> X<{n,m}> =end original 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. 以下の標準的な量指定子を使えます: X X X<*> X<+> X X<{n}> X<{n,}> X<{n,m}> =begin original * 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,m} Match at least n but not more than m times =end original * 0 回以上マッチング + 1 回以上マッチング ? 0 回または 1 回マッチング {n} 正確に n 回マッチング {n,} 最低 n 回マッチング {n,m} n 回以上 m 回以下マッチング =begin original (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 C<\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 (C<"\{">) or enclose it within square brackets (C<"[{]">). This change will allow for future syntax extensions (like making the lower bound of a quantifier optional), and better error checking of quantifiers). =end original (前述した量指定子の一つ以外のコンテキストでエスケープされない中かっこが 使われて、C<\x{...}> のような逆スラッシュ付き並びの一部ではないときには、 普通の文字として扱われるか、致命的エラーになり、どちらでも 一般的には廃止予定警告が発生します。 これをエスケープするには、逆スラッシュを前置したり (C<"\{">) 大かっこで囲んだり (C<"[{]">) できます。 この変更により、(量指定子の加減をオプションにするような) 将来の 文法の拡張ができるようになり、量指定子のより良いエラーチェックが できるようになります。 =begin original The C<"*"> quantifier is equivalent to C<{0,}>, the C<"+"> quantifier to C<{1,}>, and the C<"?"> quantifier to C<{0,1}>. I and I are limited to non-negative integral values less than a preset limit defined when perl is built. This is usually 32766 on the most common platforms. The actual limit can be seen in the error message generated by code such as this: =end original C<"*"> 量指定子は C<{0,}> と、C<"+"> 量指定子は C<{1,}> と、 C<"?"> 量指定子は C<{0,1}> と等価です。 I と I は perl をビルドしたときに定義した既定の制限より小さな 非負整数回に制限されます。 これは大抵のプラットフォームでは 32766 回になっています。 実際の制限は次のようなコードを実行すると生成されるエラーメッセージで 見ることができます: $_ **= $_ , / {$_} / for 2 .. 42; =begin original 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 C<"?">. Note that the meanings don't change, just the "greediness": X X X X X<*?> X<+?> X X<{n}?> X<{n,}?> X<{n,m}?> =end original デフォルトでは、パターンで行われる量指定は「貪欲」です; つまりそれはパターンの残りの部分が可能な範囲で、 (始めた地点から)可能な限り多くを先にあるパターンでマッチングさせます。 もし最小回数でのマッチングを行いたいのであれば、量指定子の後ろに C<"?"> を続けます。 意味は変更されずに「貪欲さ」だけを変更できます: X X X X X<*?> X<+?> X X<{n}?> X<{n,}?> X<{n,m}?> =begin original *? 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,m}? Match at least n but not more than m times, not greedily =end original *? 0 回以上の貪欲でないマッチング +? 1 回以上の貪欲でないマッチング ?? 0 回または 1 回の貪欲でないマッチング {n}? ちょうど n 回の貪欲でないマッチング (冗長) {n,}? n 回以上の貪欲でないマッチング {n,m}? n 回以上 m 回以下の貪欲でないマッチング =begin original 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. =end original 通常、パターンのうちの量指定された一部によってパターン全体が マッチングに失敗したとき、Perl はバックトラックを行います。 しかしこの振る舞いは望まれないこともあります。 そのため、Perl は「絶対最大量(possessive)」量指定形式も提供しています。 =begin original *+ 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,m}+ Match at least n but not more than m times and give nothing back =end original *+ 0 回以上マッチングして何も返さない ++ 1 回以上マッチングして何も返さない ?+ 0 回または 1 回マッチングして何も返さない {n}+ ちょうど n 回のマッチングして何も返さない (冗長) {n,}+ n 回以上のマッチングして何も返さない {n,m}+ n 回以上 m 回以下マッチングして何も返さない =begin original For instance, =end original 例えば、 'aaaa' =~ /a++a/ =begin original will never match, as the C will gobble up all the C<"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: =end original は、C が文字列中の全ての C<"a"> を飲み込んでしまい、 後に何も残さないためマッチングしません。 この機能はバックトラックするべきでない場所のヒントを perl に 与えるのに非常に便利です。 例えば、典型的な「ダブルクォート文字列のマッチング」問題で次のように 書くととても効率的になります: /"(?:[^"\\]++|\\.)*+"/ =begin original as we know that if the final quote does not match, backtracking will not help. See the independent subexpression Lpattern) >>> for more details; possessive quantifiers are just syntactic sugar for that construct. For instance the above example could also be written as follows: =end original 見ての通り最後のクォートがマッチングしなかったとき、バックトラックは 役に立ちません。 詳細は独立したサブパターン Lpattern) >>> を参照してください; 絶対最大量指定子はまさにその構文糖です。 例えばこの例は次のようにも書けます: /"(?>(?:(?>[^"\\]+)|\\.)*)"/ =begin original Note that the possessive quantifier modifier can not be be combined with the non-greedy modifier. This is because it would make no sense. Consider the follow equivalency table: =end original 絶対最大量指定修飾子は非貪欲修飾子と結合できないことに注意してください。 これは無意味だからです。 次の等価性表を考慮してください: Illegal Legal ------------ ------ X??+ X{0} X+?+ X{1} X{min,max}?+ X{min} =head3 Escape sequences (エスケープシーケンス) =begin original Because patterns are processed as double-quoted strings, the following also work: =end original パターンはダブルクォート文字列として処理されるため、 以下のエスケープ文字も動作します: X<\t> X<\n> X<\r> X<\f> X<\e> X<\a> X<\l> X<\u> X<\L> X<\U> X<\E> X<\Q> X<\0> X<\c> X<\N{}> X<\x> =begin original \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 =end original \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 的) =begin original Details are in L. =end original 詳細は L にあります。 =head3 Character Classes and other Special Escapes (文字クラス及び他の特殊なエスケープ) =begin original In addition, Perl defines the following: X<\g> X<\k> X<\K> X =end original さらに、Perl は以下のものを定義します: X<\g> X<\k> X<\K> X =begin original 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 [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 =end original 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 [5] 名前指定の後方参照 \K [6] \K の左にある物を保持、$& に含めない \N [7] \n 以外の任意の文字; /s 修飾子の影響は受けない \v [3] 垂直空白 \V [3] 垂直空白以外 \h [3] 水平空白 \H [3] 水平空白以外 \R [4] 行区切り =over 4 =item [1] =begin original See L for details. =end original 詳しくは L を参照してください。 =item [2] =begin original See L for details. =end original 詳しくは L を参照してください。 =item [3] =begin original See L for details. =end original 詳しくは L を参照してください。 =item [4] =begin original See L for details. =end original 詳しくは L を参照してください。 =item [5] =begin original See L below for details. =end original 詳しくは以下の L を参照してください。 =item [6] =begin original See L below for details. =end original 詳しくは以下のSee L を参照してください。 =item [7] =begin original Note that C<\N> has two meanings. When of the form C<\N{NAME}>, it matches the character or character sequence whose name is C; and similarly when of the form C<\N{U+I}>, it matches the character whose Unicode code point is I. Otherwise it matches any character but C<\n>. =end original C<\N> には二つの意味があることに注意してください。 C<\N{NAME}> の形式では、これは名前が C の文字または文字の並びに マッチングします; 同様に、C<\N{U+I}> の形式では、Unicode 符号位置が I の文字にマッチングします。 そうでなければ、C<\n> 以外の任意の文字にマッチングします。 =item [8] =begin original See L for details. =end original 詳しくは L を 参照してください。 =back =head3 Assertions (言明) =begin original Besides L and C<"$">|/Metacharacters>, Perl defines the following zero-width assertions: X X X X X X<\b> X<\B> X<\A> X<\Z> X<\z> X<\G> =end original L と C<"$">|/Metacharacters> の他に、 Perl は以下のゼロ幅のアサーションを定義しています: X X X X X X<\b> X<\B> X<\A> X<\Z> X<\z> X<\G> \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) =begin original A Unicode boundary (C<\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 L for details. =end original v5.22 から利用可能である Unicode 境界 (C<\b{}>) は、 Unicode で定義されたある種の基準に一致した、 二つの文字の間か、文字列の最初の文字の前か、 文字列の最後の文字の後の地点です。 詳しくは L を参照してください。 =begin original A word boundary (C<\b>) is a spot between two characters that has a C<\w> on one side of it and a C<\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 C<\W>. (Within character classes C<\b> represents backspace rather than a word boundary, just as it normally does in any double-quoted string.) The C<\A> and C<\Z> are just like C<"^"> and C<"$">, except that they won't match multiple times when the C modifier is used, while C<"^"> and C<"$"> will match at every internal line boundary. To match the actual end of the string and not ignore an optional trailing newline, use C<\z>. X<\b> X<\A> X<\Z> X<\z> X =end original 単語境界(C<\b>)はC<\W> にマッチングする文字列の始まりと終わりを 連想するような、片側を C<\w>、もう片側を C<\W> で挟まれている点です。 (文字クラスにおいては C<\b> は単語境界ではなくバックスペースを表します, ちょうどダブルクォート文字列と同じように。) C<\A> 及び C<\Z> は C<"^"> 及び C<"$"> と同様ですが、C 修飾子が 指定されているときに C<"^"> 及び C<"$"> は全ての内部的な行境界に マッチングするのに対して C<\A> 及び C<\Z> は複数回のマッチングには なりません。 文字列の本当の末尾にマッチングさせ、省略可能である末尾の改行を 無視しないようにする C<\z> を使います。 X<\b> X<\A> X<\Z> X<\z> X =begin original The C<\G> assertion can be used to chain global matches (using C), as described in L. It is also useful when writing C-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 C<\G> will match can also be influenced by using C as an lvalue: see L. Note that the rule for zero-length matches (see L) is modified somewhat, in that contents to the left of C<\G> are not counted when determining the length of the match. Thus the following will not match forever: X<\G> =end original C<\G> アサーションはグローバルなマッチング(C)を連結するために 使います; これは L にも説明されています。 これは文字列に対していくつかのパターンを次々にマッチングさせたいといった、 C 風のスキャナを書きたいときにも便利です; 以前のリファレンスを 参照してください。 C<\G> が実際にマッチングできる位置は C を左辺値として 使うことで変更できます: L を参照してください。 ゼロ幅マッチング (L を参照してください) のルールは少し変化することに注意してください、 C<\G> の左にある内容はマッチングの長さを決定するときに 数えられません。 従って次のコードは永遠にマッチングしません: X<\G> my $string = 'ABC'; pos($string) = 1; while ($string =~ /(.\G)/g) { print $1; } =begin original 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. =end original これはゼロ幅へのマッチングと見なされ、'A' を出力し終了するので、 行の中で同じ場所に二度はマッチングしません。 =begin original It is worth noting that C<\G> improperly used can result in an infinite loop. Take care when using patterns that include C<\G> in an alternation. =end original 適切に使われていない C<\G> は無限ループとなり何の価値もありません。 代替(alternation; C<|>)の中に C<\G> を含んでいるパターンを使う際には 十分注意してください。 =begin original Note also that C 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: =end original C は置換部の既に置き換えられた部分を上書きすることを拒否することにも 注意してください; 従って例えばこれは文字列の後ろ向きの反復中ではなく、 最初の反復の後に停止します: $_ = "123456789"; pos = 6; s/.(?=.\G)/X/g; print; # prints 1234X6789, not XXXXX6789 =head3 Capture groups (捕捉グループ) =begin original The grouping construct C<( ... )> 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 C<\g1> (or C<\g{1}>) for the first, C<\g2> (or C<\g{2}>) for the second, and so on. This is called a I. X X X X X X X X X<\g{1}> X<\g{-1}> X<\g{name}> X X X X X X X<%+> X<$+{name}> X<< \k >> 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, I. 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 C<"g">, and write C<"\1">, I, but there are some issues with this form, described below. =end original グループ化構文 C<( ... )> は捕捉グループを作成します (そして捕捉バッファとして 参照します)。 同じパターンの中で、あるグループの現在の内容を後で参照するには、 最初のものには C<\g1> (または C<\g{1}>) を、2 番目には C<\g2> (または C<\g{2}>) を、以下同様のものを使います。 これを I<後方参照> (backreference) と呼びます。 X X X X X X X X X<\g{1}> X<\g{-1}> X<\g{name}> X X X X X X X<%+> X<$+{name}> X<< \k >> 使う捕捉部分文字列の数に制限はありません。 グループはいちばん左の開きかっこを 1 番として番号付けされます。 グループがマッチングしなかった場合、対応する後方参照もマッチングしません。 (これはグループがオプションか、選択の異なる枝の場合に怒ることがあります。) C<"g"> を省略して C<"\1"> などと書くこともできますが、後で述べるように、 この形式にはいくらかの問題があります。 =begin original You can also refer to capture groups relatively, by using a negative number, so that C<\g-1> and C<\g{-1}> both refer to the immediately preceding capture group, and C<\g-2> and C<\g{-2}> both refer to the group before it. For example: =end original 負数を使うことで捕捉グループを相対的に参照することもできます; C<\g-1> と C<\g{-1}> は両方とも直前の捕捉グループを参照し、C<\g-2> と C<\g{-2}> は 両方ともその前のグループを参照します。 例えば: / (Y) # group 1 ( # group 2 (X) # group 3 \g{-1} # backref to group 3 \g{-3} # backref to group 1 ) /x =begin original would match the same as C. This allows you to interpolate regexes into larger regexes and not have to worry about the capture groups being renumbered. =end original は C と同じマッチングとなります。 これにより、正規表現をより大きな正規表現に挿入したときに、捕捉グループの 番号を振り直す心配をする必要がなくなります。 =begin original You can dispense with numbers altogether and create named capture groups. The notation is C<(?EIE...)> to declare and C<\g{I}> to reference. (To be compatible with .Net regular expressions, C<\g{I}> may also be written as C<\k{I}>, C<\kEIE> or C<\k'I'>.) I 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 C<(??{})>.) =end original 数値を全く使わずに、名前付き捕捉グループを作ることが出来ます。 記法は、宣言が C<(?EIE...)>、参照が C<\g{I}> です。 (.Net 正規表現との互換性のために、C<\g{I}> は C<\k{I}>, C<\kEIE>, C<\k'I'> とも書けます。) I は数字で始まってはならず、ハイフンを含んではなりません。 同じパターンの中に同じ名前の違うグループがある場合、 この名前での参照は一番左で定義されたものを仮定します。 名前付きグループも絶対や相対番号付けに含まれるので、 番号で参照することも出来ます。 (C<(??{})> が必要な場合でも名前付き捕捉グループを使うことが出来ます。) =begin original 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, whichever comes first. (See L.) You can refer to them by absolute number (using C<"$1"> instead of C<"\g1">, I); or by name via the C<%+> hash, using C<"$+{I}">. =end original 捕捉グループの内容は動的スコープを持ち、パターンの外側でも現在のブロックの 末尾か次のマッチングの成功のどちらか早いほうまで利用可能です。 (L を参照してください。) これらに対して (C<"\g1"> などの代わりに C<"$1"> を使って) 絶対値で 参照するか、C<"$+{I}"> を使って C<%+> 経由で名前で参照できます。 =begin original 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 C, and C<$a> contained C<"\g1">, and C<$b> contained C<"37">, you would get C which is probably not what you intended. =end original 名前付き捕捉グループを参照するには中かっこが必要です; しかし、絶対数値や相対数値の場合はオプションです。 より小さい文字列を結合して正規表現を作る場合は中かっこを使う方が安全です。 例えば C で C<$a> に C<"\g1"> を含み、 C<$b> に C<"37"> を含んでいるとき、 結果は C となりますが、おそらく望んでいたものではないでしょう。 =begin original The C<\g> and C<\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 C<\1>, C<\2>, I., 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 C<\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 C<\10> as a backreference only if at least 10 left parentheses have opened before it. Likewise C<\11> is a backreference only if at least 11 left parentheses have opened before it. And so on. C<\1> through C<\9> are always interpreted as backreferences. There are several examples below that illustrate these perils. You can avoid the ambiguity by always using C<\g{}> or C<\g> if you mean capturing groups; and for octal constants always using C<\o{}>, or for C<\077> and below, using 3 digits padded with leading zeros, since a leading zero implies an octal constant. =end original C<\g> と C<\k> の記法は Perl 5.10.0 で導入されました。 それより前には名前付きや相対数値指定の捕捉グループはありませんでした。 絶対数値指定のグループは C<\1>, C<\2> などとして参照でき、この記法はまだ 受け付けられます (そしておそらくいつも受け付けられます)。 しかし、これは 9 を越える捕捉グループがあるとあいまいさがあります; C<\10> は 10 番目の捕捉グループとも、8 進数で 010 の文字(ASCII で バックスペース)とも解釈できます。 Perl はこのあいまいさを以下のように解決します; C<\10> の場合、これの前に少なくとも 10 の左かっこがある場合にのみ これを後方参照として解釈します。 同様に、C<\11> はその前に少なくとも 11 の左かっこがある場合にのみ これを後方参照として解釈します。 以下同様です。 C<\1> から C<\9> は常に後方参照として解釈されます。 これを図示するいくつかの例が後にあります。 捕捉グループを意味する場合は常に C<\g{}> や C<\g> を使うことで あいまいさを避けられます; そして 8 進定数については常に C<\o{}> を使うか、C<\077> 以下の場合は、 先頭に 0 を付けて 3 桁にします; なぜなら先頭に 0 が付くと 8 進定数を仮定するからです。 =begin original The C<\I> notation also works in certain circumstances outside the pattern. See L below for details. =end original C<\I> 記法は、ある種の状況ではパターンの外側でも動作します。 詳しくは後述する L を参照して下さい。 =begin original Examples: =end original 例: s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words /(.)\g1/ # find first doubled char and print "'$1' is the first doubled character\n"; /(?.)\k/ # ... 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 =begin original Several special variables also refer back to portions of the previous match. C<$+> returns whatever the last bracket match matched. C<$&> returns the entire matched string. (At one point C<$0> did also, but now it returns the name of the program.) C<$`> returns everything before the matched string. C<$'> returns everything after the matched string. And C<$^N> contains whatever was matched by the most-recently closed group (submatch). C<$^N> can be used in extended patterns (see below), for example to assign a submatch to a variable. X<$+> X<$^N> X<$&> X<$`> X<$'> =end original いくつかの特殊変数もまた以前のマッチングの一部を参照しています。 C<$+> は最後のマッチングしたブラケットマッチングを返します。 C<$&> はマッチングした文字列全体を返します。 (一頃は C<$0> もそうでしたが、現在ではこれはプログラム名を返します。) C<$`> はマッチングした文字列の前の全てを返します。 C<$'> はマッチングした文字列の後の全てを返します。 そして C<$^N> には一番最後に閉じたグループ(サブマッチング)に マッチングしたものを含んでいます。 C<$^N> は例えばサブマッチングを変数に格納するため等に拡張パターンの中でも 利用できます(後述)。 X<$+> X<$^N> X<$&> X<$`> X<$'> =begin original These special variables, like the C<%+> hash and the numbered match variables (C<$1>, C<$2>, C<$3>, I.) are dynamically scoped until the end of the enclosing block or until the next successful match, whichever comes first. (See L.) X<$+> X<$^N> X<$&> X<$`> X<$'> X<$1> X<$2> X<$3> X<$4> X<$5> X<$6> X<$7> X<$8> X<$9> =end original C<%+> ハッシュのような特殊変数と、数値によるマッチング変数 (C<$1>, C<$2>, C<$3> など)はブロックの終端または次のマッチング 成功までのどちらか先に満たした方の、動的なスコープを持ちます。 (L を参照してください。) X<$+> X<$^N> X<$&> X<$`> X<$'> X<$1> X<$2> X<$3> X<$4> X<$5> X<$6> X<$7> X<$8> X<$9> =begin original B: 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. =end original B<補足>: Perl において失敗したマッチングはマッチング変数をリセットしません; これはより特殊化させる一連のテストを書くことや、 最善のマッチングを書くことを容易にします。 =begin original B: If your code is to run on Perl 5.16 or earlier, beware that once Perl sees that you need one of C<$&>, C<$`>, or C<$'> anywhere in the program, it has to provide them for every pattern match. This may substantially slow your program. =end original B<警告>: あなたのコードが Perl 5.16 以前で実行されるものの場合、 Perl は、一旦プログラム中のどこかで C<$&>, C<$`>, C<$'> の いずれかを必要としていることを見つけると、全てのパターンマッチングで それらを提供しなければなあらないことに注意してください。 これはあなたのプログラムを大幅に遅くさせるでしょう。 =begin original Perl uses the same mechanism to produce C<$1>, C<$2>, I, 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 C<(?: ... )> instead.) But if you never use C<$&>, C<$`> or C<$'>, then patterns I capturing parentheses will not be penalized. So avoid C<$&>, C<$'>, and C<$`> 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. X<$&> X<$`> X<$'> =end original Perl は C<$1>, C<$2> 等の生成にも同じメカニズムを使っているので、 キャプチャのかっこに含まれるそれぞれのパターンにも 同じ料金を払っています。 (グループ化の振る舞いを維持しつつこのコストを削減するには 拡張正規表現 C<(?: ... )> を代わりに使います (訳注:Perl拡張というだけで C 修飾子は不要)。) ですが C<$&>, C<$`> または C<$'> を一度も使わなければ、 キャプチャのかっこをI<もたない>パターンではこの不利益はなくなります。 この為、可能であれば C<$&>, C<$'>, 及び C<$`> を削除しましょう: しかしそれができなかった(そしてそれらを 本当に理解しているアルゴリズムがあるのであれば)、一旦 それらを使った時点でそれ以降は自由にそれらを使うことができます; なぜならあなたは(一度使った時点で)既に代価を払っているので。 X<$&> X<$`> X<$'> =begin original Perl 5.16 introduced a slightly more efficient mechanism that notes separately whether each of C<$`>, C<$&>, and C<$'> 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. =end original Perl 5.16 では、C<$`>, C<$&>, C<$'> のそれぞれが現れるかどうかを 個別に記録するという少し効率的な機構が導入され、 従って文字列の一部分だけコピーするようになりました。 Perl 5.20 では、全く遅くならない遙かに効率的なコピーオンライト機構を 導入しました。 =begin original As another workaround for this problem, Perl 5.10.0 introduced C<${^PREMATCH}>, C<${^MATCH}> and C<${^POSTMATCH}>, which are equivalent to C<$`>, C<$&> and C<$'>, B that they are only guaranteed to be defined after a successful match that was executed with the C

(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 C<$`>, C<$&> and C<$'>, and C

is ignored. X

X

=end original この問題に対するもう一つの解決策として、Perl 5.10.0 からは C<$`>, C<$&>, C<$'> と 等価だけれども C

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

は無視されます。 X

X

=head2 Quoting metacharacters (メタ文字のクォート) =begin original Backslashed metacharacters in Perl are alphanumeric, such as C<\b>, C<\w>, C<\n>. Unlike some other regular expression languages, there are no backslashed symbols that aren't alphanumeric. So anything that looks like C<\\>, C<\(>, C<\)>, C<\[>, C<\]>, C<\{>, or C<\}> 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: =end original Perl において逆スラッシュで表現されるメタ文字は C<\b>, C<\w>, C<\n> のように英数字です。 他の正規表現言語とは異なり、英数字でない逆スラッシュ付きシンボルは ありません。 なので C<\\>, C<\(>, C<\)>, C<\[>, C<\]>, C<\{>, or C<\}> といったものは 全てメタ文字ではなくリテラル文字です。 これはパターンで使いたい文字列の中で正規表現のメタ文字としての特殊な意味を 無効化またはクォートするための一般的な指標として使われてきました。 「単語」でない全ての文字は単にクォートします: $pattern =~ s/(\W)/\\$1/g; =begin original (If C is set, then this depends on the current locale.) Today it is more common to use the C> function or the C<\Q> metaquoting escape sequence to disable all metacharacters' special meanings like this: =end original (もし C が有効であれば、これは現在のロケールに依存します。) 今日では特殊な意味を持つメタ文字を全て無効にするためには次のように C> 関数か C<\Q> メタクォート エスケープシーケンスを使うのがより一般的です: /$unquoted\Q$quoted\E$unquoted/ =begin original Beware that if you put literal backslashes (those not inside interpolated variables) between C<\Q> and C<\E>, double-quotish backslash interpolation may lead to confusing results. If you I to use literal backslashes within C<\Q...\E>, consult L. =end original C<\Q> 及び C<\E> の間でリテラルとして逆スラッシュをおくとき (埋め込んだ変数の中でではない)には、二重にクォートした逆スラッシュの 埋め込みは困惑した結果となるでしょう。 もし C<\Q...\E> でリテラルとしての逆スラッシュを使う I<必要がある> のなら、 L を参照してください。 =begin original C and C<\Q> are fully described in L. =end original C と C<\Q> は L に完全に記述されています。 =head2 Extended Patterns (拡張パターン) =begin original Perl also defines a consistent extension syntax for features not found in standard tools like B and B. 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. =end original Perl は B や B といった標準的なツールでは見られない機能のための 拡張構文も定義しています。 これらのほとんどの構文は対のかっことかっこ内の最初に疑問符の形をとります。 疑問符の後の文字で拡張を区別します。 =begin original 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.... =end original 疑問符は 1) それが古い正規表現で使われることは稀であること、そして 2) それを見かけると何が行われるのか本当に「疑問に」思って止まることから、 これのためと最小マッチング構成子のために選ばれました。 これが心理学です…。 =over 4 =item C<(?#text)> X<(?#)> =begin original A comment. The text is ignored. Note that Perl closes the comment as soon as it sees a C<")">, so there is no way to put a literal C<")"> in the comment. The pattern's closing delimiter must be escaped by a backslash if it appears in the comment. =end original コメント。 テキストは無視されます。 Perl は C<")"> を見つけると直ぐにコメントを閉じる点に注意してください; この為リテラル C<")"> をコメント中におくことはできません。 パターンの閉じ区切り文字がコメントに見えるようなものなら、 逆スラッシュでエスケープしなければなりません。 =begin original See Lx> for another way to have comments in patterns. =end original パターンの中にコメントを入れるもう一つの方法については Lx> を参照してください。 =begin original Note that a comment can go just about anywhere, except in the middle of an escape sequence. Examples: =end original コメントは、エスケープシーケンスの途中を除いて、 どこにでも入れることができることに注意してください。 例: 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}/ =item C<(?adlupimnsx-imnsx)> =item C<(?^alupimnsx)> X<(?)> X<(?^)> =begin original One or more embedded pattern-match modifiers, to be turned on (or turned off if preceded by C<"-">) for the remainder of the pattern or the remainder of the enclosing pattern group (if any). =end original 一つもしくは複数のパターンマッチング修飾子; パターンの残りまたは(もしあれば)包含しているパターングループの残りで 有効にする(または C<"-"> が前置されていれば解除する)。 =begin original 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 C<(?i)> at the front of the pattern. For example: =end original これは設定ファイルから読む、引数から取る、どこかのテーブルで 指定されている箇所から動的生成されたパターンを使うときに特に便利です。 パターンの一部では大文字小文字を区別したいけれども別の箇所では 区別しないといったケースを考えてみます: 区別をしない場所では 単にパターンの先頭に C<(?i)> を含めるだけです。 例えば: $pattern = "foobar"; if ( /$pattern/i ) { } # more flexible: $pattern = "(?i)foobar"; if ( /$pattern/ ) { } =begin original These modifiers are restored at the end of the enclosing group. For example, =end original これらの修飾子は包含しているグループの最後で復元(restore)されます。 例えば、 ( (?i) blah ) \s+ \g1 =begin original will match C in any case, some spaces, and an exact (I!) repetition of the previous word, assuming the C modifier, and no C modifier outside this group. =end original は C に大文字小文字の区別なくマッチングし、 いくつかの空白、そして前の単語その物(I<大文字小文字の区別まで含めて>!)に 再度マッチングします; ここではこのグループの外側で C 修飾子を持ち、 C 修飾子を持たないものとします。 =begin original These modifiers do not carry over into named subpatterns called in the enclosing group. In other words, a pattern such as C<((?i)(?&NAME))> does not change the case-sensitivity of the C<"NAME"> pattern. =end original これらの修飾子は囲まれたグループで呼び出された名前付き部分パターンには 持ち越されません。 言い換えると、C<((?i)(?&NAME))> のようなパターンは、 C<"NAME"> パターンが大文字小文字を認識するのを変更しません。 =begin original A modifier is overridden by later occurrences of this construct in the same scope containing the same modifier, so that =end original 修飾子は、同じスコープ内で同じ修飾子を含む この構文が後に出現すると上書きされるので: /((?im)foo(?-m)bar)/ =begin original matches all of C case insensitively, but uses C rules for only the C portion. The C<"a"> flag overrides C as well; likewise C overrides C<"a">. The same goes for C<"x"> and C. Hence, in =end original は、C のすべてに大文字小文字を区別せずにマッチングしますが、 C 部分のみに C の規則を使います。 C<"a"> フラグは C も上書きします; 同様に、C も C<"a">を上書きします。 同じことが C<"x"> と C についても当てはまります。 したがって: /(?-x)foo/xx =begin original both C and C are turned off during matching C. And in =end original C と C は両方とも、C のマッチング中はオフになります。 そして: /(?x)foo/x =begin original C but NOT C is turned on for matching C. (One might mistakenly think that since the inner C<(?x)> is already in the scope of C, that the result would effectively be the sum of them, yielding C. It doesn't work that way.) Similarly, doing something like C<(?xx-x)foo> turns off all C<"x"> behavior for matching C, it is not that you subtract 1 C<"x"> from 2 to get 1 C<"x"> remaining. =end original C にマッチングする間、C ではなく C がオンになります。 (内部 C<(?x)> はすでに C の範囲内にあるので、結果は実質的に それらの和になり、C が生成されると誤って考えるかもしれません。 そうはなりません。) 同様に、C<(?xx-x)foo> のようなことをすると、C とマッチングする間 C<"x"> の動作がすべてオフになります; 二つの C<"x"> から一つ引いて一つの C<"x"> が残るということにはなりません。 =begin original Any of these modifiers can be set to apply globally to all regular expressions compiled within the scope of a C. See L. =end original それらの変更のどれもセットでき、Cのスコープ内でグローバルに 全てのコンパイルされた正規表現に適用されます。L を見てください。 =begin original Starting in Perl 5.14, a C<"^"> (caret or circumflex accent) immediately after the C<"?"> is a shorthand equivalent to C. Flags (except C<"d">) may follow the caret to override it. But a minus sign is not legal with it. =end original Perl 5.14から、C<"^">(キャレットか曲折アクセント)がC<"?">のすぐ 後ろにつくと、C と同じになります。フラグ(C<"d">以外の) をキャレットに続けることで、上書きできます。 ですが、マイナス記号は一緒に使えません。 =begin original Note that the C<"a">, C<"d">, C<"l">, C<"p">, and C<"u"> modifiers are special in that they can only be enabled, not disabled, and the C<"a">, C<"d">, C<"l">, and C<"u"> modifiers are mutually exclusive: specifying one de-specifies the others, and a maximum of one (or two C<"a">'s) may appear in the construct. Thus, for example, C<(?-p)> will warn when compiled under C; C<(?-d:...)> and C<(?dl:...)> are fatal errors. =end original C<"a">, C<"d">, C<"l">, C<"p">, C<"u"> 修飾子は有効にできるのみで、 無効にはできない点、 そして C<"a">, C<"d">, C<"l">, C<"u"> 修飾子は 互いに排他であるという点で特別です: 一つを指定すると他のものの指定を解除し、構文中に最大で一つ (または二つの C<"a">) だけが現れます。 従って 例えば C<(?-p)> は C の下でコンパイルされると 警告を発します; C<(?-d:...)> と C<(?dl:...)> は致命的エラーです。 =begin original Note also that the C<"p"> modifier is special in that its presence anywhere in a pattern has a global effect. =end original パターン中のどこにあってもグローバルな影響があるという意味で C<"p"> 修飾子が特別であることにも注意してください。 =item C<(?:pattern)> X<(?:)> =item C<(?adluimnsx-imnsx:pattern)> =item C<(?^aluimnsx:pattern)> X<(?^:)> =begin original This is for clustering, not capturing; it groups subexpressions like C<"()">, but doesn't make backreferences as C<"()"> does. So =end original これはキャプチャではなくクラスタです; これは C<"()"> のように部分式を グループ化しますが C<"()"> が行うような後方参照は行いません。 つまり、 @fields = split(/\b(?:a|b|c)\b/) =begin original matches the same field delimiters as =end original 次と同じフィールド区切り文字にマッチングしますが: @fields = split(/\b(a|b|c)\b/) =begin original but doesn't spit out the delimiters themselves as extra fields (even though that's the behaviour of L when its pattern contains capturing groups). It's also cheaper not to capture characters if you don't need to. =end original (例えそれが捕捉グループを含むときの L の振る舞いで あったとしても) 区切り文字自身を余計なフィールドとして引き出しません。 また不要であれば文字のキャプチャを行わないため低コストです。 =begin original Any letters between C<"?"> and C<":"> act as flags modifiers as with C<(?adluimnsx-imnsx)>. For example, =end original C<"?"> 及び C<":"> の間の文字は C<(?adluimnsx-imnsx)> のような フラグ修飾子として動作します。 例えば、 /(?s-i:more.*than).*million/i =begin original is equivalent to the more verbose =end original はより冗長に書けば以下と等価です /(?:(?s-i)more.*than).*million/i =begin original Note that any C<()> constructs enclosed within this one will still capture unless the C modifier is in effect. =end original これの中の C<()> 構文は、C が有効でない限りまだ捕捉することに 注意してください。 =begin original Like the L construct, C and C<"a"> override each other, as do C and C<"x">. They are not additive. So, doing something like C<(?xx-x:foo)> turns off all C<"x"> behavior for matching C. =end original L 構文と同様、C と C<"x">と同様に、C と C<"a"> は互いに上書きします。 これらは加法的ではありません。 したがって、C<(?xx-x:foo)> のようなことを行うと、 C にマッチングする間、C<"x"> の動作がすべてオフになります。 =begin original Starting in Perl 5.14, a C<"^"> (caret or circumflex accent) immediately after the C<"?"> is a shorthand equivalent to C. Any positive flags (except C<"d">) may follow the caret, so =end original Perl 5.14 から、C<"^">(キャレットあるいは曲折アクセント)が C<"?"> のすぐ 後ろにつくと、C と同じになります。 どのような肯定のフラグ(C<"d"> 以外の)もキャレットに続けることができます; そのため、 (?^x:foo) =begin original is equivalent to =end original は、以下と同じになります。 (?x-imns:foo) =begin original The caret tells Perl that this cluster doesn't inherit the flags of any surrounding pattern, but uses the system defaults (C), modified by any flags specified. =end original キャレットは、Perlにこのクラスターはパターンの周りのどのフラグも 引き継がずに、代わりに、システムのデフォルトのフラグ (C) を使うことを教えます; 指定されている他のフラグによって変更されます。 =begin original The caret allows for simpler stringification of compiled regular expressions. These look like =end original キャレットはより簡単なコンパイルされた正規表現の文字列化をすることが できます。次のものは (?^:pattern) =begin original 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. =end original キャレットとコロンの間には、デフォルトでないフラグがありません。 このような文字列化を見るテストには、したがって、システムのデフォルトのフラグを その中にハードコードする必要はなく、ただキャレットを使います。新しいフラグが Perlに追加されたら、キャレットを展開した意味はそれらのフラグのためのデフォルトを 含むように変更されます; そのために、このテストは、それでも何も変えずに 動くでしょう。 =begin original Specifying a negative flag after the caret is an error, as the flag is redundant. =end original キャレットの後ろに否定のフラグを付けると、余計なフラグであるとして、 エラーになります。 =begin original Mnemonic for C<(?^...)>: A fresh beginning since the usual use of a caret is to match at the beginning. =end original C<(?^...)>の覚え方: 新鮮な開始; 通常のキャレットの使い方は文字列の開始の マッチなので。 =item C<(?|pattern)> X<(?|)> X =begin original 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. =end original これは各代替分岐において捕捉グループを同じ番号から始める特殊な 属性を持っている、「ブランチリセット(branch reset)」パターンです。 これは perl 5.10.0 から提供されています。 =begin original Capture groups are numbered from left to right, but inside this construct the numbering is restarted for each branch. =end original 捕捉グループは左から右へと番号が振られますが、この構成子の内側では 各分岐毎に番号はリセットされます。 =begin original 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. =end original 各分岐内での番号付けは通常通りに行われ、この構成子の後に続くグループは その中で捕捉グループが一番多かった分岐のみが 格納されていたかのように番号付けされていきます。 =begin original This construct is useful when you want to capture one of a number of alternative matches. =end original この構成子はいくつかの代替マッチングの1つを捕捉したいときに便利です。 =begin original Consider the following pattern. The numbers underneath show in which group the captured content will be stored. =end original 以下のパターンを想像してみてください。 下側の番号は内容の格納されるグループを示します。 # before ---------------branch-reset----------- after / ( a ) (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x # 1 2 2 3 2 3 4 =begin original 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: =end original 名前付き捕捉と枝リセットパターンを組み合わせて使うときには注意してください。 名前付き捕捉は捕捉を保持している番号付きグループへの別名として 実装されていて、枝リセットパターンの実装を妨害します。 枝リセットパターンで名前付き捕捉を使うときは、それぞれの代替で 同じ名前を同じ順番で使うのが最良です: /(?| (? x ) (? y ) | (? z ) (? w )) /x =begin original Not doing so may lead to surprises: =end original そうしないと驚くことになります: "12" =~ /(?| (? \d+ ) | (? \D+))/x; say $+{a}; # Prints '12' say $+{b}; # *Also* prints '12'. =begin original The problem here is that both the group named C<< a >> and the group named C<< b >> are aliases for the group belonging to C<< $1 >>. =end original ここでの問題は、C<< a >> という名前のグループと C<< b >> という名前の が両方ともグループ C<< $1 >> への別名であることです。 =item Lookaround Assertions X X X X =begin original Lookaround assertions are zero-width patterns which match a specific pattern without including it in C<$&>. 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. =end original 先読み及び後読みの言明(assertion)は C<$&> の中に 含めない特定のパターンにマッチングするゼロ幅のパターンです。 正の言明はその部分パターンがマッチングしたときにマッチングし、 負の言明はその部分パターンが失敗したときにマッチングします。 後読みのマッチングは今のマッチング位置までのテキストにマッチングし、 先読みの言明は今のマッチング位置の先にあるテキストにマッチングします。 =over 4 =item C<(?=pattern)> X<(?=)> X X =begin original A zero-width positive lookahead assertion. For example, C matches a word followed by a tab, without including the tab in C<$&>. =end original ゼロ幅の正の先読み言明。 例えば、C はタブが続く単語にマッチングしますが、タブは C<$&> に含まれません。 =item C<(?!pattern)> X<(?!)> X X =begin original A zero-width negative lookahead assertion. For example C 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. =end original ゼロ幅の負の先読み言明。 例えば C は "bar" が続かない全ての "foo" にマッチングします。 しかしながら先読みと後読みは同じ物では ない点に注意してください。 これを後読みに使うことはできません。 =begin original If you are looking for a "bar" that isn't preceded by a "foo", C will not do what you want. That's because the C<(?!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). =end original もし "foo" が前にない "bar" を探しているのなら、 C では欲しい物にはなりません。 なぜなら C<(?!foo)> は次のものが "foo" ではないとだけいっているのです -- そしてそうではなく、そこには "bar" があるので、"foobar" はマッチングします。 (後述の) 後方参照を使ってください。 =item C<(?<=pattern)> =item C<\K> X<(?<=)> X X X<\K> =begin original A zero-width positive lookbehind assertion. For example, C matches a word that follows a tab, without including the tab in C<$&>. Works only for fixed-width lookbehind. =end original ゼロ幅の正の後読みの言明。 例えば、C は タブに続く単語にマッチングしますが、タブは $& に 含まれません。 固定幅の後読みのみが動作します。 =begin original There is a special form of this construct, called C<\K> (available since Perl 5.10.0), which causes the regex engine to "keep" everything it had matched prior to the C<\K> and not include it in C<$&>. This effectively provides variable-length lookbehind. The use of C<\K> inside of another lookaround assertion is allowed, but the behaviour is currently not well defined. =end original (Perl 5.10.0 から利用可能な) C<\K> というこの構成子の特殊な形式もあります; これは正規表現エンジンに対してそれが C<\K> までにマッチングした すべてのものを"取っておいて"、C<$&> には含めないようにさせます。 これは事実上可変長の後読みを提供します。 他の先読み及び後読みの言明の中での利用も可能ですが、その振る舞いは 今のところあまり定義されていません。 =begin original For various reasons C<\K> may be significantly more efficient than the equivalent C<< (?<=...) >> construct, and it is especially useful in situations where you want to efficiently remove something following something else in a string. For instance =end original いくつかの理由から、C<\K> は等価な C<< (?<=...) >> 構成子より非常に効率的で、文字列の中で何かに続いている何かを効率的に 取り除きたいようなシチュエーションで効果的に役立ちます。 例えば s/(foo)bar/$1/g; =begin original can be rewritten as the much more efficient =end original 次のようにより効率的に書き直せます s/foo\Kbar//g; =item C<(? X<(? X X =begin original A zero-width negative lookbehind assertion. For example C matches any occurrence of "foo" that does not follow "bar". Works only for fixed-width lookbehind. =end original ゼロ幅の負の後読みの言明。 例えば C は "bar" に続いていない任意の "foo" に マッチングします。 固定幅の後読みのみが動作します。 =back =item C<< (?pattern) >> =item C<(?'NAME'pattern)> X<< (?) >> X<(?'NAME')> X X =begin original A named capture group. Identical in every respect to normal capturing parentheses C<()> but for the additional fact that the group can be referred to by name in various regular expression constructs (like C<\g{NAME}>) and can be accessed by name after a successful match via C<%+> or C<%->. See L for more details on the C<%+> and C<%-> hashes. =end original 名前付の捕捉グループ。 通常のキャプチャかっこ C<()> と同様ですがそれに加えて、 グループは(C<\g{NAME}> のように) 様々な正規表現構文で名前で参照でき、 マッチングに成功したあと C<%+> を C<%-> を使って名前によって アクセスできます。 C<%+> 及び C<%-> ハッシュに関する詳細は L を 参照してください。 =begin original If multiple distinct capture groups have the same name then the C<$+{NAME}> will refer to the leftmost defined group in the match. =end original 複数の異なる捕捉グループが同じ名前を持っていたときには C<$+{NAME}> はマッチングの中で一番左で定義されたグループを参照します。 =begin original The forms C<(?'NAME'pattern)> and C<< (?pattern) >> are equivalent. =end original 二つの形式 C<(?'NAME'pattern)> 及び C<< (?pattern) >> は等価です。 =begin original B 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 =end original B<補足:> これを構成する記法は 類似していている .NET での正規表現と 同じですが、振る舞いは異なります。 Perl ではグループは名前がついているかどうかにかかわらず順番に番号が 振られます。 従って次のパターンにおいて /(x)(?y)(z)/ =begin original C<$+{I}> will be the same as C<$2>, and C<$3> will contain 'z' instead of the opposite which is what a .NET regex hacker might expect. =end original C<$+{I}> は C<$2> と同じであり、C<$3> には .NET 正規表現に 慣れた人が予測するのとは異なり 'z' が含まれます。 =begin original Currently I is restricted to simple identifiers only. In other words, it must match C or its Unicode extension (see L), though it isn't extended by the locale (see L). =end original 現在のところ I はシンプルな識別子のみに制限されています。 言い換えると、C または その Unicode 拡張にマッチングしなければなりません (L も参照); しかしロケールでは拡張されません (L 参照)。 =begin original B In order to make things easier for programmers with experience with the Python or PCRE regex engines, the pattern C<< (?PENAMEEpattern) >> may be used instead of C<< (?pattern) >>; however this form does not support the use of single quotes as a delimiter for the name. =end original B<補足:> Python や PCRE 正規表現エンジンになれたプログラマが 楽になるように、C<< (?pattern) >> の代わりに C<< (?PENAMEEpattern) >> のパターンを使うことも できます; しかしこの形式は名前のデリミタとして シングルクォートの使用はサポートされていません。 =item C<< \k >> =item C<< \k'NAME' >> =begin original 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. =end original 名前による後方参照。 数値によってではなく名前によってグループを指定する点を除いて、名前による 後方参照と似ています。 もし同じ名前の複数のグループがあったときには現在のマッチングで 一番左に定義されているグループを参照します。 =begin original It is an error to refer to a name not defined by a C<< (?) >> earlier in the pattern. =end original パターン内で C<< (?) >> によって定義されていない名前を 参照するとエラーになります。 =begin original Both forms are equivalent. =end original 両方の形式とも等価です。 =begin original B In order to make things easier for programmers with experience with the Python or PCRE regex engines, the pattern C<< (?P=NAME) >> may be used instead of C<< \k >>. =end original B<補足:> Python や PCRE 正規表現エンジンになれたプログラマが楽に なるように、C<< \k >> の代わりに C<< (?P=NAME) >> のパターンを使うこともできます。 =item C<(?{ code })> X<(?{})> X X X =begin original B: 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 L. =end original B<警告>: この機能を安全に使うには、その制限について理解することが必要です。 副作用を持つコードの実行は今後の正規表現エンジンの最適化の影響で バージョン間で必ずしも同じになるとは限らないでしょう。 これに関するさらなる情報については、L を 参照してください。 =begin original This zero-width assertion executes any embedded Perl code. It always succeeds, and its return value is set as C<$^R>. =end original このゼロ幅アサーションは埋め込まれた任意の Perl コードを実行します。 これは常に(正規表現として)成功し、返り値は C<$^R> に設定されます。 =begin original 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 =end original リテラルなパターンでは、このコードは周りのコードと同時にパースされます。 このパターンの中では、 論理的にバランスが取れる閉じかっこが現れるまで、 制御文字は一時的に perl パーサーに渡されます。 これはリテラル文字列の中の配列添字表現の扱われ方と似ています; 例えば: "abc$array[ 1 + f('[') + g()]def" =begin original In particular, braces do not need to be balanced: =end original 特に、中かっこはバランスが取れている必要はありません: s/abc(?{ f('{'); })/def/ =begin original 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": =end original 実行時に展開されてコンパイルされるパターンの中であっても、 リテラルなコードブロックは perl のコンパイル時に一度だけコンパイルされます; 次のものは "ABCD" と表示されます: print "D"; my $qr = qr/(?{ BEGIN { print "A" } })/; my $foo = "foo"; /$foo$qr(?{ BEGIN { print "B" } })/; BEGIN { print "C" } =begin original 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, C must be in scope. This is to stop user-supplied patterns containing code snippets from being executable. =end original コードのテキストがソースコードの /pattern/ としてリテラルに現れるのではなく、 実行時の情報から派生したものであるパターンでは、 コードはパターンがコンパイルされるのと同時にコンパイルされ、 セキュリティー上の理由により、C が スコープ内になければなりません。 これは、実行可能なコード片を含む、ユーザーが提供したパターンを止めるためです。 =begin original In situations where you need to enable this with C, you should also have taint checking enabled. Better yet, use the carefully constrained evaluation within a Safe compartment. See L for details about both these mechanisms. =end original C でこれを有効にする必要がある場合、 汚染チェックも有効にするべきです。 出来れば、Safe 区画の中で注意深く制限された評価を使ってください。 これら両方の機構に関する詳細については L を参照してください。 =begin original From the viewpoint of parsing, lexical variable scope and closures, =end original パース、レキシカル変数スコープ、クロージャの観点から、 /AAA(?{ BBB })CCC/ =begin original behaves approximately like =end original はおよそ次のように振る舞います: /AAA/ && do { BBB } && /CCC/ =begin original Similarly, =end original 同様に、 qr/AAA(?{ BBB })CCC/ =begin original behaves approximately like =end original はおよそ次のように振る舞います: sub { /AAA/ && do { BBB } && /CCC/ } =begin original In particular: =end original 特に: { my $i = 1; $r = qr/(?{ print $i })/ } my $i = 2; /$r/; # prints "1" =begin original Inside a C<(?{...})> block, C<$_> refers to the string the regular expression is matching against. You can also use C to know what is the current position of matching within this string. =end original C<(?{...})> ブロックの中では C<$_> は正規表現をマッチングさせている文字列を 参照します。 C を使ってこの文字列で現在のマッチング位置を知ることもできます。 =begin original The code block introduces a new scope from the perspective of lexical variable declarations, but B from the perspective of C 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 L). For example, =end original コードブロックは、C や同様のローカル化の振る舞いの観点 B<ではなく> レキシカル変数宣言の観点での新しいスコープを導入します。 従って、同じパターンで後に出てくるコードブロックは 前に出てきたローカル化された値が見えるままです。 これらの蓄積されたローカル化は、マッチングが成功するか、 アサートがバックトラックした時点で巻き戻されます (L と比較してください)。 例えば: $_ = '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; =begin original will initially increment C<$cnt> up to 8; then during backtracking, its value will be unwound back to 4, which is the value assigned to C<$res>. At the end of the regex execution, C<$cnt> will be wound back to its initial value of 0. =end original これはまず C<$cnt> は 8 までインクリメントされます; それからバックトラックの間に、この値は 4 まで巻き戻され、 その値が C<$res> に代入されます。 正規表現実行の最後では、$cnt は初期値である 0 に巻き戻ります。 =begin original This assertion may be used as the condition in a =end original このアサーションは条件として: (?(condition)yes-pattern|no-pattern) =begin original switch. If I used in this way, the result of evaluation of C is put into the special variable C<$^R>. This happens immediately, so C<$^R> can be used from other C<(?{ code })> assertions inside the same regular expression. =end original スイッチとして使われるかもしれません。 この方法で使われI<なかった>のなら、C の評価結果は特殊変数 C<$^R> に おかれます。 これはすぐに行われるので C<$^R> は同じ正規表現内の他の C アサーションで使うことができます。 =begin original The assignment to C<$^R> above is properly localized, so the old value of C<$^R> is restored if the assertion is backtracked; compare L. =end original この C<$^R> への設定は適切にlocal化されるため、C<$^R> の古い値は バックトラックしたときには復元されます; L を 見てください。 =begin original Note that the special variable C<$^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: =end original 特殊変数 C<$^N> は、一緒にネストしたかっこの数を数えずに一つ前の マッチング結果を捕捉するコードブロックで特に有用です。 例えば: $_ = "The brown fox jumps over the lazy dog"; /the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i; print "color = $color, animal = $animal\n"; =item C<(??{ code })> X<(??{})> X X X =begin original B: 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 L. =end original B<警告>: この機能を安全に使うには、その制限について理解することが必要です。 副作用を持つコードの実行は今後の正規表現エンジンの最適化の影響で バージョン間で必ずしも同じになるとは限らないでしょう。 これに関するさらなる情報については、L を 参照してください。 =begin original This is a "postponed" regular subexpression. It behaves in I the same way as a C<(?{ code })> code block as described above, except that its return value, rather than being assigned to C<$^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. =end original これは「先送りされた」正規部分表現です。 これは上述の C<(?{ code })> コードブロックと I<正確に> 同じように 振る舞いますが、その返り値は、C<$^R> に代入されるのではなく、 パターンとして扱われ、 それが文字列の場合はコンパイルされ(あるいは qr// オブジェクトの場合は そのまま使われ)、それからこの構文の代わりに挿入されていたかのように マッチングします。 =begin original 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"; =end original 副パターンのマッチングの間、副マッチングの間有効な独自の捕捉グループを 持ちますが、一旦制御が主パターンに戻ると捨てられます。 例えば、次のマッチングは、内側のパターンで "B" と "BB" にマッチングし、 一方外側のパターンは "A" を捕捉します; my $inner = '(.)\1'; "ABBA" =~ /^(.)(??{ $inner })\1/; print $1; # prints "A"; =begin original 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 C<$1>, I., to refer to the enclosing pattern's capture groups.) Thus, although =end original 内側のパターンが外側で定義された捕捉グループを参照する方法は ないことに注意してください。 (コードブロック自体は、内側のパターンの捕捉グループを参照するために C<$1> などを使えます。) 従って: ('a' x 100)=~/(??{'(.)' x 100})/ =begin original I match, it will I set C<$1> on exit. =end original これはマッチング I<します> が、終了時に C<$1> は設定 I<されません>。 =begin original The following pattern matches a parenthesized group: =end original 次のパターンはかっこで囲まれたグループにマッチングします: $re = qr{ \( (?: (?> [^()]+ ) # Non-parens without backtracking | (??{ $re }) # Group with matching parens )* \) }x; =begin original See also L)>|/(?PARNO) (?-PARNO) (?+PARNO) (?R) (?0)> for a different, more efficient way to accomplish the same task. =end original 同じタスクを行う別の、より効率的な方法として L)>|/(?PARNO) (?-PARNO) (?+PARNO) (?R) (?0)> も 参照してください。 =begin original 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. =end original 入力を消費しない多すぎる先送りされた正規表現を実行するのも 致命的なエラーとなります。 これが起きる深度は perl にコンパイルされているので、カスタムビルドで これを変更できます。 =item C<(?I)> C<(?-I)> C<(?+I)> C<(?R)> C<(?0)> X<(?PARNO)> X<(?1)> X<(?R)> X<(?0)> X<(?-1)> X<(?+1)> X<(?-PARNO)> X<(?+PARNO)> X X X X X X =begin original 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. =end original 再帰部分パターン。 現在のパターンの与えられた捕捉バッファの内容を独立した 部分パターンとして扱って、 文字列の現在の位置でマッチングしようとします。 後方参照のような呼び出し元からの捕捉状態に関する情報は 部分パターンで利用可能ですが、 部分パターンで設定された捕捉バッファは呼び出し元には見えません。 =begin original Similar to C<(??{ 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 C<(??{ code })> recursive patterns have access to their caller's match state, so one can use backreferences safely. =end original C<(??{ code })> と似ていますが、 コードの実行を伴なわず、返されたパターン文字列をコンパイルもしません; その代わりに、指定された捕捉グループに含まれる現在のパターンの一部を、 現在の位置でマッチングすべき独立したパターンとして扱います。 また、捕捉バッファの扱いも異なります; C<(??{ code })> と異なり、再帰パターンはその呼び出し元のマッチング 状態にアクセスすることが出来るので、安全に後方参照を使えます。 =begin original I is a sequence of digits (not starting with 0) whose value reflects the paren-number of the capture group to recurse to. C<(?R)> recurses to the beginning of the whole pattern. C<(?0)> is an alternate syntax for C<(?R)>. If I 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 C<(?-1)> refers to the most recently declared group, and C<(?+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 B included. =end original I はその値が再帰させる捕捉グループのかっこ番号を反映する一連の 数字からなります(そして 0 からは始まりません)。 C<(?R)> はパターン全体の最初から再帰します。 C<(?0)> は C<(?R)> の別の構文です。 I の前に正符号または負符号がついていた場合には相対的な位置として 使われます; 負数であれば前の捕捉グループを、正数であれば続く 捕捉グループを示します。 従って C<(?-1)> は一番最近宣言されたグループを参照し、C<(?+1)> は次に 宣言されるグループを参照します。 相対再帰の数え方は相対後方参照とは違って、グループに閉じていない再帰は 含まB<れる>ことに注意してください, =begin original The following pattern matches a function C which may contain balanced parentheses as the argument. =end original 以下のパターンは引数にバランスのとれたかっこを含んでいるかもしれない関数 C にマッチングします。 $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; =begin original If the pattern was used as follows =end original このパターンを以下のように使うと, 'foo(bar(baz)+baz(bop))'=~/$re/ and print "\$1 = $1\n", "\$2 = $2\n", "\$3 = $3\n"; =begin original the output produced should be the following: =end original 次のように出力されます: $1 = foo(bar(baz)+baz(bop)) $2 = (bar(baz)+baz(bop)) $3 = bar(baz)+baz(bop) =begin original 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. =end original もし対応する捕捉グループが定義されていなかったときには致命的な エラーとなります。 入力を消費しない深い再帰も致命的なエラーとなります。 これが起きる深度は perl にコンパイルされているので、カスタムビルドで これを変更できます。 =begin original The following shows how using negative indexing can make it easier to embed recursive patterns inside of a C construct for later use: =end original 以下に後で使うパターンのために、C 構成子内で再帰を埋め込むのに 負数の参照を使うとどのように容易になるかを示します: my $parens = qr/(\((?:[^()]++|(?-1))*+\))/; if (/foo $parens \s+ \+ \s+ bar $parens/x) { # do something here... } =begin original B 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 C<(?i:(?1))> or C<(?:(?i)(?1))> do not affect how the sub-pattern will be processed. =end original B<補足> このパターンは PCRE や Python での等価な形式の構成子と同じように 振る舞うわけではありません。 Perl においては再帰グループの中にバックトラックできますが、PCRE や Python ではグループへの再帰はアトミックに扱われます。 また、修飾子はコンパイル時に解決されるので、C<(?i:(?1))> や C<(?:(?i)(?1))> といった構成子はサブパターンがどのように処理されたかに 影響されません。 =item C<(?&NAME)> X<(?&NAME)> =begin original Recurse to a named subpattern. Identical to C<(?I)> except that the parenthesis to recurse to is determined by name. If multiple parentheses have the same name, then it recurses to the leftmost. =end original 名前付きサブパターンへの再帰。 再帰するかっこが名前によって決定される点以外は C<(?I)> と等価です。 もし複数のかっこで同じ名前を持っていた場合には一番左のものに再帰します。 =begin original It is an error to refer to a name that is not declared somewhere in the pattern. =end original パターンのどこでも宣言されていない名前の参照はエラーになります。 =begin original B In order to make things easier for programmers with experience with the Python or PCRE regex engines the pattern C<< (?P>NAME) >> may be used instead of C<< (?&NAME) >>. =end original B<補足:> Python または PCRE 正規表現エンジンに慣れているプログラマが 簡単になるように C<< (?&NAME) >> の代わりに C<< (?P>NANE) >> を使うことも できます。 =item C<(?(condition)yes-pattern|no-pattern)> X<(?()> =item C<(?(condition)yes-pattern)> =begin original Conditional expression. Matches C if C yields a true value, matches C otherwise. A missing pattern always matches. =end original 条件付き式。 C が真なら C にマッチングし、さもなければ C にマッチングします。 パターンがなければ常にマッチングします。 =begin original C<(condition)> should be one of: =end original C<(condition)> は次のいずれかです: =over 4 =item an integer in parentheses (かっこでくるまれた数値) =begin original (which is valid if the corresponding pair of parentheses matched); =end original (対応するかっこ対がマッチングしたときに有効); =item a lookahead/lookbehind/evaluate zero-width assertion; (先読み/後読み/ゼロ幅で評価される言明) =item a name in angle brackets or single quotes (角かっこもしくはシングルクォートでくるまれた名前) =begin original (which is valid if a group with the given name matched); =end original (その名前のグループがマッチングしたときに有効); =item the special symbol C<(R)> (特殊なシンボル C<(R)>) =begin original (true when evaluated inside of recursion or eval). Additionally the C<"R"> may be followed by a number, (which will be true when evaluated when recursing inside of the appropriate group), or by C<&NAME>, in which case it will be true only when evaluated during recursion in the named group. =end original (再帰または eval 内で評価されているときに真)。 加えて C<"R"> には数字(対応するグループ内で再帰しているときに真)、もしくは C<&NAME>、こちらの時はその名前のグループで再帰している時にのみ真、を 続けることもできます。 =back =begin original Here's a summary of the possible predicates: =end original 可能な述語の要約を次に示します: =over 4 =item C<(1)> C<(2)> ... =begin original Checks if the numbered capturing group has matched something. Full syntax: C<< (?(1)then|else) >> =end original その番号の捕捉グループが何かにマッチングしたかどうかを調べます。 完全な文法: C<< (?(1)then|else) >> =item C<(EIE)> C<('I')> =begin original Checks if a group with the given name has matched something. Full syntax: C<< (?()then|else) >> =end original その名前のグループが何かにマッチングしたかどうかを調べます。 完全な文法: C<< (?()then|else) >> =item C<(?=...)> C<(?!...)> C<(?<=...)> C<(? =begin original Checks whether the pattern matches (or does not match, for the C<"!"> variants). Full syntax: C<< (?(?=lookahead)then|else) >> =end original パターンがマッチングするか (あるいは C<"!"> 版はマッチングしないか) を チェックします。 完全な文法: C<< (?(?=lookahead)then|else) >> =item C<(?{ I })> =begin original Treats the return value of the code block as the condition. Full syntax: C<< (?(?{ code })then|else) >> =end original コードブロックの返り値を条件として扱います。 完全な文法: C<< (?(?{ code })then|else) >> =item C<(R)> =begin original Checks if the expression has been evaluated inside of recursion. Full syntax: C<< (?(R)then|else) >> =end original 式が再帰の中で評価されているかどうかを調べます。 完全な文法: C<< (?(R)then|else) >> =item C<(R1)> C<(R2)> ... =begin original Checks if the expression has been evaluated while executing directly inside of the n-th capture group. This check is the regex equivalent of =end original 式がその n 番目の捕捉グループのすぐ内側で実行されているかどうかを調べます。 これは次のものと等価な正規表現です if ((caller(0))[3] eq 'subname') { ... } =begin original In other words, it does not check the full recursion stack. =end original 言い換えると、これは完全な再帰スタックを調べるわけではありません。 =begin original Full syntax: C<< (?(R1)then|else) >> =end original 完全な文法: C<< (?(R1)then|else) >> =item C<(R&I)> =begin original Similar to C<(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 C<(?&I)> to disambiguate). It does not check the full stack, but only the name of the innermost active recursion. Full syntax: C<< (?(R&name)then|else) >> =end original C<(R1)> と似ていて、この述語はその名前のつけられている一番左のグループの すぐ内側で実行されているかどうかをしらべます(一番左は C<(?&I)> と 同じロジックです)。 これは完全なスタックを調べずに、一番内部のアクティブな再帰の名前だけを 調べます。 完全な文法: C<< (?(R&name)then|else) >> =item C<(DEFINE)> =begin original In this case, the yes-pattern is never directly executed, and no no-pattern is allowed. Similar in spirit to C<(?{0})> but more efficient. See below for details. Full syntax: C<< (?(DEFINE)definitions...) >> =end original この場合において、yes-pattern は直接は実行されず、no-pattern は 許可されていません。 C<(?{0})> と似ていますがより効率的です。 詳細は次のようになります。 完全な文法: C<< (?(DEFINE)definitions...) >> =back =begin original For example: =end original 例: m{ ( \( )? [^()]+ (?(1) \) ) }x =begin original matches a chunk of non-parentheses, possibly included in parentheses themselves. =end original これはかっこ以外からなる固まりかかっこの中にあるそれらにマッチングします。 =begin original A special form is the C<(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. =end original C<(DEFINE)> は特殊な形式で、これはその yes-pattern を直接は実行せず、 no-pattern も許可していません。 これは再帰メカニズムの中で利用することでのみ実行されるサブパターンの 定義を許可します。 これによって、選んだパターンと一緒に正規表現ルールを定義できます。 =begin original 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. =end original この使い方において、DEFINE ブロックはパターンの最後におくこと、 そしてそこで定義する全てのサブパターンに名前をつけることが 推奨されています。 =begin original 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. =end original また、この方法によって定義されるパターンはその処理に関してそんなに 賢い訳ではないので効率的でないことに価値は何もないでしょう。 =begin original An example of how this might be used is as follows: =end original これをどのように使うかの例を次に示します: /(?(?&NAME_PAT))(?(?&ADDRESS_PAT)) (?(DEFINE) (?....) (?....) )/x =begin original 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 C<$+{NAME_PAT}> would not be defined even though C<$+{NAME}> would be. =end original 再帰の内側でマッチングした捕捉グループは再帰から戻った後には アクセスできないため、余分な捕捉グループの レイヤは必要な点に注意してください。 従って C<$+{NAME}> が定義されていても C<$+{NAME_PAT}> は定義されません。 =begin original Finally, keep in mind that subpatterns created inside a DEFINE block count towards the absolute and relative number of captures, so this: =end original 最後に、DEFINE ブロックの内側で作られた副パターンは捕捉の絶対及び 相対番号で数えることに注意してください; 従ってこうすると: my @captures = "a" =~ /(.) # First capture (?(DEFINE) (? 1 ) # Second capture )/x; say scalar @captures; =begin original Will output 2, not 1. This is particularly important if you intend to compile the definitions with the C operator, and later interpolate them in another pattern. =end original 1 ではなく 2 を出力します。 これは、C 演算子で定義をコンパイルして、 後で他のパターンの中で展開することを意図している場合に特に重要です。 =item C<< (?>pattern) >> X X X X =begin original An "independent" subexpression, one which matches the substring that a I C would match if anchored at the given position, and it matches I. This construct is useful for optimizations of what would otherwise be "eternal" matches, because it will not backtrack (see L). It may also be useful in places where the "grab all you can, and do not give anything back" semantic is desirable. =end original 「独立した」部分式、I<スタンドアロンの> C がその場所に 固定されてマッチングする部分文字列にマッチングし、 I<その文字列以外にはなにも>マッチングしません。 この構成子は他の"外部"マッチングになる最適化に便利です; なぜならこれはバックトラックしないためです(L 参照)。 これは "できる限りを取り込んで、後は戻らない"セマンティクスが 必要な場所でも便利です。 =begin original For example: C<< ^(?>a*)ab >> will never match, since C<< (?>a*) >> (anchored at the beginning of string, as above) will match I characters C<"a"> at the beginning of string, leaving no C<"a"> for C to match. In contrast, C will match the same as C, since the match of the subgroup C is influenced by the following group C (see L). In particular, C inside C will match fewer characters than a standalone C, since this makes the tail match. =end original 例: C<< ^(?>a*)ab >> は何もマッチングしません、 なぜなら C<< (?>a*) >> (前述のように、文字列の開始で固定されます)は 文字列のはじめにある全ての文字 C<"a"> にマッチングし、 C のマッチングのための C<"a"> を残さないためです。 対照的に、C は C と同じようにマッチングします、 これはサブグループ C のマッチングは次のグループ C の影響を 受けるためです (L 参照)。 特に、C の中の C は単独の C より短い文字にマッチングします; これによって最後のマッチングが行えるようになります。 =begin original C<< (?>pattern) >> does not disable backtracking altogether once it has matched. It is still possible to backtrack past the construct, but not into it. So C<< ((?>a*)|(?>b*))ar >> will still match "bar". =end original C<< (?>pattern) >> は、一旦マッチングしたら、全くバックトラックを 無効にしません。 未だこの構文の前までバックトラックする可能性はありますが、構文の中に バックトラックすることはありません。 従って C<< ((?>a*)|(?>b*))ar >> は "bar" にマッチングするままです。 =begin original An effect similar to C<< (?>pattern) >> may be achieved by writing C<(?=(pattern))\g{-1}>. This matches the same substring as a standalone C, and the following C<\g{-1}> eats the matched string; it therefore makes a zero-length assertion into an analogue of C<< (?>...) >>. (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.) =end original C<< (?>pattern) >> と似た効果は C<(?=(pattern))\g{-1}> でも達成できます。 これは単独の C と同じ部分文字列にマッチングし、それに続く C<\g{-1}> が マッチングした文字列を消費します; これはゼロ幅の言明が C<< (?>...) >> の類似を作るためです。 (この2つの構成子は後者はグループをキャプチャするため、 それに続く正規表現の残りで後方参照の順序をずらす点で違いがあります。) =begin original Consider this pattern: =end original 次のパターンを考えてみてください: m{ \( ( [^()]+ # x+ | \( [^()]* \) )+ \) }x =begin original 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 C<(.+)+> is doing, and C<(.+)+> is similar to a subpattern of the above pattern. Consider how the pattern above detects no-match on C<((()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 =end original これは 2 段階までのかっこでくるまれた空でないグループに効率的に マッチングします。 しかしながら、これはマッチングするグループがなかったときに長い 文字列においてはほとんど永遠に戻りません。 これは長い文字列をいくつかの部分文字列に分解する方法がいくつもあるためです。 これは C<(.+)+> が行うことでもあり、C<(.+)+> は このパターンの 部分パターンと似ています。 このパターンが C<((()aaaaaaaaaaaaaaaaaa> にはマッチングしないことを どうやって検出するかを少し考えてみましょう、 しかしここでは余計な文字を2倍にしてみます。 この指数的なパフォーマンスはプログラムのハングアップとして表面化します。 しかしながら、このパターンに小さな変更をいれてみます, m{ \( ( (?> [^()]+ ) # change x+ above to (?> x+ ) | \( [^()]* \) )+ \) }x =begin original which uses C<< (?>...) >> 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 C<"a">s. Be aware, however, that, when this construct is followed by a quantifier, it currently triggers a warning message under the C pragma or B<-w> switch saying it C<"matches null string many times in regex">. =end original これは上で行っているように C<< (?>...) >> マッチングを 使っています(これは自身で確認してみるとよいでしょう)が、 しかし 1000000 個の C<"a"> からなる似た文字列を使ってみると、4 分の 1 の 時間で完了します。 しかしながら、この構文は量指定子が引き続くと現在のところ C プラグマまたは B<-w> スイッチの影響下では C<"matches null string many times in regex"> (正規表現において空文字列に何回もマッチングしました) という警告を 発するでしょう。 =begin original On simple groups, such as the pattern C<< (?> [^()]+ ) >>, a comparable effect may be achieved by negative lookahead, as in C<[^()]+ (?! [^()] )>. This was only 4 times slower on a string with 1000000 C<"a">s. =end original パターン C<< (?> [^()]+ ) >> のような簡単なグループでは、 比較できる影響は C<[^()]+ (?! [^()] )> のように負の先読みの 言明で達することができます。 これは 1000000 個の C<"a"> からなる文字列において 4 倍だけ遅くなります。 =begin original The "grab all you can, and do not give anything back" semantic is desirable in many situations where on the first sight a simple C<()*> looks like the correct solution. Suppose we parse text with comments being delimited by C<"#"> followed by some optional (horizontal) whitespace. Contrary to its appearance, C<#[ \t]*> I 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: =end original 最初の C<()*> のような正しい解法となる多くの状況において 「できる限りを取り込んで、後は戻らない」セマンティクスが望まれるものです。 任意で(水平)空白の続く C<"#"> によって区切られるコメントのついたテキストの パースを考えてみます。 その出現と対比して、C<#[ \t]*> はコメント区切りにマッチングする 正しい部分式ではありません; なぜならパターンの残りがそれのマッチングを 作ることができるのならそれはいくつかの空白を「あきらめてしまう」ためです。 正しい回答は以下のいずれかです: (?>#[ \t]*) #[ \t]*(?![ \t]) =begin original For example, to grab non-empty comments into C<$1>, one should use either one of these: =end original 例えば空でないコメントを C<$1> に取り込むためには次のいずれかを使います: / (?> \# [ \t]* ) ( .+ ) /x; / \# [ \t]* ( [^ \t] .* ) /x; =begin original Which one you pick depends on which of these expressions better reflects the above specification of comments. =end original 選んだ方はコメントの仕様をより適切に反映した式に依存します。 =begin original In some literature this construct is called "atomic matching" or "possessive matching". =end original いくつかの書籍においてこの構成子は「アトミックなマッチング」 または「絶対最大量マッチング(possessive matching)」と呼ばれます。 =begin original Possessive quantifiers are equivalent to putting the item they are applied to inside of one of these constructs. The following equivalences apply: =end original 絶対最大量指定子はそれが適用されている項目をこれらの構成子の中に置くことと 等価です。 以下の等式が適用されます: Quantifier Form Bracketing Form --------------- --------------- PAT*+ (?>PAT*) PAT++ (?>PAT+) PAT?+ (?>PAT?) PAT{min,max}+ (?>PAT{min,max}) =item C<(?[ ])> =begin original See L. =end original L を参照してください。 =begin original Note that this feature is currently L; using it yields a warning in the C category. =end original この機能は現在 L<実験的|perlpolicy/experimental> です; これを使うと C カテゴリの警告が発生します。 =back =head2 Backtracking X X (バックトラック) =begin original 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 L. =end original 補足: このセクションでは正規表現の振る舞いに関する抽象的な概要を 説明します。 可能な代替におけるマッチングの選択におけるルールの厳密な(そして複雑な) 説明は L を参照してください。 =begin original A fundamental feature of regular expression matching involves the notion called I, which is currently used (when needed) by all regular non-possessive expression quantifiers, namely C<"*">, C<*?>, C<"+">, C<+?>, C<{n,m}>, and C<{n,m}?>. Backtracking is often optimized internally, but the general principle outlined here is valid. =end original 正規表現マッチングの基本的な機能には最近(必要であれば)すべての強欲でない 正規表現量指定子、つまり、 C<"*">, C<*?>, C<"+">, C<+?>, C<{n,m}>, C<{n,m}?> で 使われる I<バックトラッキング> と呼ばれる概念が含まれています。 バックトラックはしばしば内部で最適化されますが、ここで概説する一般的な 原則は妥当です。 =begin original For a regular expression to match, the I 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. =end original 正規表現がマッチングする時、その正規表現の一部ではなく、 I<全体> がマッチングしなければなりません。 そのためもしパターンの前半にパターンの後半部分を失敗させてしまう 量指定子が含まれているのなら、マッチングングエンジンはいったん戻って 開始位置を再計算します -- これがバックトラッキングと呼ばれる所以です。 =begin original 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.": =end original バックトラッキングの例をあげてみます: "Food is on the foo table." という 文字列の中で "foo" に続く単語を取り出してください: $_ = "Food is on the foo table."; if ( /\b(foo)\s+(\w+)/i ) { print "$2 follows $1.\n"; } =begin original When the match runs, the first part of the regular expression (C<\b(foo)>) finds a possible match right at the beginning of the string, and loads up C<$1> with "Foo". However, as soon as the matching engine sees that there's no whitespace following the "Foo" that it had saved in C<$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." =end original マッチングが実行される時、正規表現の最初の部分 (C<\b(foo)>) は開始文字列の 右側で可能なマッチングを探します; そして C<$1> に "Foo" をロードします。 しかし、すぐにマッチングエンジンは C<$1> に保存した "Foo" の後に空白が 無いことを見つけ、それが失敗だったことを検出して仮にマッチングさせた 場所の 1 文字後から開始します。 この時次の "foo" の出現まで進みます。 この時に正規表現は完全にマッチングし、予測した出力 "table follows foo." を 得ます。 =begin original Sometimes minimal matching can help a lot. Imagine you'd like to match everything between "foo" and "bar". Initially, you write something like this: =end original 最小マッチングが役立つこともあります。 "foo" と "bar" の間の全てにマッチングしたいと考えてください。 最初に、次のように書くかもしれません: $_ = "The food is under the bar in the barn."; if ( /foo(.*)bar/ ) { print "got <$1>\n"; } =begin original Which perhaps unexpectedly yields: =end original しかしこれは考えたのと違う結果となるでしょう: got =begin original That's because C<.*> was greedy, so you get everything between the I "foo" and the I "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. =end original これは C<.*> が貪欲であり、そのために I<最初の> "foo" と I<最後の> "bar" の間にある全てを取り出してしまいます。 次に "foo" とその後の最初の "bar" の間にあるテキストを取り出す 最小マッチングを使ったもっと効率的な方法を示します: if ( /foo(.*?)bar/ ) { print "got <$1>\n" } got =begin original 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: =end original 別の例も出してみます。 文字列の最後にある数字にマッチングさせて、そのマッチングの前の部分も 保持させてみましょう。 そしてあなたは次のように書くかもしれません。 $_ = "I have 2 numbers: 53147"; if ( /(.*)(\d*)/ ) { # Wrong! print "Beginning is <$1>, number is <$2>.\n"; } =begin original That won't work at all, because C<.*> was greedy and gobbled up the whole string. As C<\d*> can match on an empty string the complete regular expression matched successfully. =end original これは全く動作しません、なぜなら C<.*> は貪欲であり文字列全体を 飲み込んでしまいます。 C<\d*> は空の文字列にマッチングできるので正規表現は完全に正常に マッチングします。 Beginning is , number is <>. =begin original Here are some variants, most of which don't work: =end original 動作しない主なバリエーションをあげておきます: $_ = "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"; } } =begin original That will print out: =end original これらの結果は次のようになります: (.*)(\d*) <> (.*)(\d+) <7> (.*?)(\d*) <> <> (.*?)(\d+) <2> (.*)(\d+)$ <7> (.*?)(\d+)$ <53147> (.*)\b(\d+)$ <53147> (.*\D)(\d+)$ <53147> =begin original 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. =end original このように、これは幾分トリッキーです。 重要なのは正規表現は成功の定義を定める主張の集合にすぎないことを 認識することです。 特定の文字列で成功となる定義には 0, 1 または複数の違ったやり方が存在します。 そしてもし成功する複数の方法が存在するのなら成功したうちのどれが目的と するものなのかを知るためにバックトラッキングを理解しておく必要があります。 =begin original 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 =end original 前読みの言明及び否定を使っている時にはこれはますますトリッキーになります。 "123" が後ろに続かない数字以外の列を探したいと考えてみてください。 あなたは次のように書くかもしれません。 $_ = "ABC123"; if ( /^\D*(?!123)/ ) { # Wrong! print "Yup, no 123 in $_\n"; } =begin original 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: =end original ですがこれはマッチングしません; 少なくともなってほしかったようには。 これは文字列の中に 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)/; =begin original This prints =end original これは次の出力となります 2: got ABC 3: got AB 4: got ABC =begin original 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 (C<\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 C<$x>, following 0 or more non-digits, you have something that's not 123?" If the pattern matcher had let C<\D*> expand to "ABC", this would have caused the whole pattern to fail. =end original テスト 3 はテスト 1 のより一般的なバージョンなのでそれが失敗すると 考えたかもしれません。 この 2 つの重要な違いは、テスト 3 には量指定子(C<\D*>)が含まれているので テスト1ではできなかったバックトラッキングを行うことが できるところにあります。 ここであなたは「C<$x> のはじめで 0 個以上の非数字があるから 123 ではない 何かを得られるんじゃないの?」と聞くでしょう。 このパターンマッチングが C<\D*> を "ABC" に展開させると これはパターン全体を失敗させることになります。 =begin original The search engine will initially match C<\D*> with "ABC". Then it will try to match C<(?!123)> with "123", which fails. But because a quantifier (C<\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. =end original 探索エンジンは最初に C<\D*> を "ABC" にマッチングさせます。 そして C<(?!123)> を "123" にマッチングさせ、これは失敗します。 けれども量指定子 (C<\D*>) が正規表現の中で使われているので、探索エンジンは バックトラックしてこの正規表現全体をマッチングさせるように異なるマッチングを 行うことができます。 =begin original The pattern really, I wants to succeed, so it uses the standard pattern back-off-and-retry and lets C<\D*> expand to just "AB" this time. Now there's indeed something following "AB" that is not "123". It's "C123", which suffices. =end original このパターンは本当に、I<本当に> 成功したいので、これは標準的なパターンの 後退再試行を行い、この時に C<\D*> を "AB" のみに展開させます。 そして確かに "AB" の後ろは "123" ではありません。 "C123" は十分満たしています。 =begin original We can deal with this by using both an assertion and a negation. We'll say that the first part in C<$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: =end original これは言明と否定の両方を使うことで処理することができます。 C<$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 =begin original 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: C 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. C 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. =end original 言い換えると、このそれぞれの次にある2つのゼロ幅の言明はちょうど何か組み込みの 言明を使ったかのようにそれらがともに AND されているかのように動作します: C は行の始まりで且つ同時に行の終了でる時にのみマッチングします。 もっと深部での真実は、併記された正規表現は垂直線を使って明示的に OR を 書いたとき以外は常に AND を意味します。 C は、"a" がゼロ幅の言明ではなく 1 文字幅の言明なので異なる場所で マッチングが行われはしますが、 "a" にマッチング且つ(そして) "b" に マッチングということを意味します。 =begin original B: 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: =end original B<警告>: 特にコンパイルされた正規表現はマッチングのために できる限りのバックトラックを非常に多くの回数行うので 解くために指数的な時間を必要とすることがあります。 例えば、正規表現エンジンの内部で行われる最適化がなかったときには、次の評価は 尋常じゃないくらい長時間かかります: 'aaaaaaaaaaaa' =~ /((a{0,5}){0,5})*[c]/ =begin original And if you used C<"*">'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 C<{0,5}> instead of C<"*"> on the external group, no current optimization is applicable, and the match takes a long time to finish. =end original そしてもし内側のグループで 0 から 5 回にマッチングを制限する代わりに C<"*"> を使うと、永久に、またはスタックを使い果たすまで 実行し続けることになります。 その上、これらの最適化は常にできるわけではありません。 例えば、外側のグループで C<"*"> の代わりに C<{0,5}> を使ったときに、現在の 最適化は適用されません; そしてマッチングが終わるまでの長い時間が 必要になります。 =begin original A powerful tool for optimizing such beasts is what is known as an "independent group", which does not backtrack (see Lpattern) >>>). 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 I have influenced the following match, see Lpattern) >>>. =end original そのような野獣のような最適化のためのパワフルなツールとして 知られているものに、「独立グループ」があります; これはバックトラックを 行いません (Lpattern) >>> を参照)。 ゼロ幅の先読み/後読みの言明も「論理的な」文脈なので末尾のマッチングを バックトラックしません: マッチングが関連して考慮されるかどうかだけです。 先読みの言明の副作用がそれに続くマッチングに影響する I<かもしれない> 例は、 Lpattern) >>> を参照してください。 =head2 Special Backtracking Control Verbs (特殊なバックトラック制御記号) =begin original These special patterns are generally of the form C<(*I:I)>. Unless otherwise stated the I argument is optional; in some cases, it is mandatory. =end original これらの特殊なパターンは C<(*I:I)> という一般形式を持っています。 特に記されていない限り、I はオプションです; 一部の場合では、 これは必須です。 =begin original Any pattern containing a special backtracking verb that allows an argument has the special behaviour that when executed it sets the current package's C<$REGERROR> and C<$REGMARK> variables. When doing so the following rules apply: =end original 引数を許可する特殊バックトラック制御記号を含んでいる全てのパターンは、 それが実行されると現在のパッケージの C<$REGERROR> 及び C<$REGMARK> 変数を 設定する特殊な振る舞いを持っています。 これが行われる時以下の手順が適用されます。 =begin original On failure, the C<$REGERROR> variable will be set to the I value of the verb pattern, if the verb was involved in the failure of the match. If the I part of the pattern was omitted, then C<$REGERROR> will be set to the name of the last C<(*MARK:NAME)> pattern executed, or to TRUE if there was none. Also, the C<$REGMARK> variable will be set to FALSE. =end original 失敗時には C<$REGERROR> 変数には、記号がマッチングの失敗の中で 使われていたのならその記号パターンの I の値がセットされます。 もしパターンの I 部分が省略されていたときには、C<$REGERROR> には 最後に実行された C<(*MARK:NAME)> パターンの名前、またはそれもなければ 真に設定されます。 また、C<$REGMARK> 変数は偽に設定されます。 =begin original On a successful match, the C<$REGERROR> variable will be set to FALSE, and the C<$REGMARK> variable will be set to the name of the last C<(*MARK:NAME)> pattern executed. See the explanation for the C<(*MARK:NAME)> verb below for more details. =end original マッチングの成功時には、C<$REGERROR> 変数は偽に設定され、C<$REGMARK> 変数には 最後に実行された C<(*MARK:NAME)> パターンの名前が設定されます。 詳細は C<(*MARK:NAME)> 記号の説明を参照してください。 =begin original B C<$REGERROR> and C<$REGMARK> are not magic variables like C<$1> and most other regex-related variables. They are not local to a scope, nor readonly, but instead are volatile package variables similar to C<$AUTOLOAD>. They are set in the package containing the code that I the regex (rather than the one that compiled it, where those differ). If necessary, you can use C to localize changes to these variables to a specific scope before executing a regex. =end original B<補足:> C<$REGERROR> 及び C<$REGMARK> は C<$1> や他の多くの 正規表現関連の変数のようにマジック変数ではありません。 それらはスコープ内にローカルにならず、読み込み専用でもありませんが、 C<$AUTOLOAD> と似た揮発するパッケージ変数です。 これらには正規表現が I<実行される> コードを含むパッケージが設定されます (コンパイルされるコードではありません; これは異なることがあります)。 必要な場合は、正規表現を実行する前に これらの変数の変更を特定のスコープ内に留めるために C を使えます。 =begin original If a pattern does not contain a special backtracking verb that allows an argument, then C<$REGERROR> and C<$REGMARK> are not touched at all. =end original もしパターンが引数を許可する特殊バックトラック記号を含んでなかった場合には、 C<$REGERROR> 及び C<$REGMARK> は全く触られません。 =over 3 =item Verbs (動詞) =over 4 =item C<(*PRUNE)> C<(*PRUNE:NAME)> X<(*PRUNE)> X<(*PRUNE:NAME)> =begin original This zero-width pattern prunes the backtracking tree at the current point when backtracked into on failure. Consider the pattern C (*PRUNE) I/>, where I and I are complex patterns. Until the C<(*PRUNE)> verb is reached, I may backtrack as necessary to match. Once it is reached, matching continues in I, 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. =end original このゼロ幅のパターンは失敗でバックトラックしてきたときに現在の位置で バックトラックツリーを刈り取ります。 C (*PRUNE) I/> というパターンで I も I も複雑なパターンである時を 考えてみます。 C<(*PRUNE)> に達するまでは、I はマッチングに必要であれば バックトラックしていきます。 しかし一旦そこに達して I に続くと、そこでも必要に応じてバックトラックします; しかしながら、B がマッチングしなかったときにはそれ以上のバックトラックは 行われず、現在の開始位置でのマッチングはすぐに失敗します。 =begin original The following example counts all the possible matching strings in a pattern (without actually matching any of them). =end original 次の例ではパターンに対してマッチングできるすべての文字列を(実際には マッチングさせずに)数えます。 'aaab' =~ /a+b?(?{print "$&\n"; $count++})(*FAIL)/; print "Count=$count\n"; =begin original which produces: =end original この出力: aaab aaa aa a aab aa a ab a Count=9 =begin original If we add a C<(*PRUNE)> before the count like the following =end original 次のように数える前に C<(*PRUNE)> を加えると 'aaab' =~ /a+b?(*PRUNE)(?{print "$&\n"; $count++})(*FAIL)/; print "Count=$count\n"; =begin original we prevent backtracking and find the count of the longest matching string at each matching starting point like so: =end original バックトラックを妨げ次のように各開始位置での一番長いマッチング文字列を 数えるようになります: aaab aab ab Count=3 =begin original Any number of C<(*PRUNE)> assertions may be used in a pattern. =end original 1つのパターン内で C<(*PRUNE)> 言明はいくつでも使えます。 =begin original See also C<<< L<< /(?>pattern) >> >>> and possessive quantifiers for other ways to control backtracking. In some cases, the use of C<(*PRUNE)> can be replaced with a C<< (?>pattern) >> with no functional difference; however, C<(*PRUNE)> can be used to handle cases that cannot be expressed using a C<< (?>pattern) >> alone. =end original バックトラックを制御する他の方法として C<<< L<< /(?>pattern) >> >>> 及び絶対最大量指定子も参照してください。 幾つかのケースにおいては C<(*PRUNE)> の利用は機能的な違いなしに C<< (?>pattern) >> で置き換えることができます; しかしながら C<(*PRUNE)> は C<< (?>pattern) >> 単独では表現できないケースを扱うために使えます。 =item C<(*SKIP)> C<(*SKIP:NAME)> X<(*SKIP)> =begin original This zero-width pattern is similar to C<(*PRUNE)>, except that on failure it also signifies that whatever text that was matched leading up to the C<(*SKIP)> pattern being executed cannot be part of I 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). =end original このゼロ幅のパターンは C<*PRUNE> と似ていますが、実行されている C<(*SKIP)> パターンまでにマッチングしたテキストはこのパターンの I<どの>マッチングの一部にもならないことを示します。 これは正規表現エンジンがこの位置まで失敗として「スキップ」して(マッチングに 十分な空間があれば)再びマッチングを試みることを効率的に意味します。 =begin original The name of the C<(*SKIP:NAME)> pattern has special significance. If a C<(*MARK:NAME)> was encountered while matching, then it is that position which is used as the "skip point". If no C<(*MARK)> of that name was encountered, then the C<(*SKIP)> operator has no effect. When used without a name the "skip point" is where the match point was when executing the C<(*SKIP)> pattern. =end original C<(*SKIP:NAME)> パターンの名前部分には特別な意味があります。 もしマッチングにおいて C<(*MARK:NAME)> に遭遇すると、それは「スキップ 位置」として使われる位置になります。 その名前の C<(*MARK)> と東宮していなければ、C<(*SKIP)> 操作は効果を 持ちません。 名前がなければ「スキップ位置」は C<(*SKIP)> パターンの実行されたときに マッチングポイントが使われます。 =begin original Compare the following to the examples in C<(*PRUNE)>; note the string is twice as long: =end original 以下の例を C<(*PRUNE)> と比べてみてください; 文字列が2倍になってることに注意してください: 'aaabaaab' =~ /a+b?(*SKIP)(?{print "$&\n"; $count++})(*FAIL)/; print "Count=$count\n"; =begin original outputs =end original これの出力は aaab aaab Count=2 =begin original Once the 'aaab' at the start of the string has matched, and the C<(*SKIP)> executed, the next starting point will be where the cursor was when the C<(*SKIP)> was executed. =end original いったん文字列の最初の 'aaab' がマッチングして、C<(*SKIP)> が実行されると、 次の開始位置は C<(*SKIP)> が実行されたときのカーソルがいた位置になります。 =item C<(*MARK:NAME)> C<(*:NAME)> X<(*MARK)> X<(*MARK:NAME)> X<(*:NAME)> =begin original 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 C<(*SKIP)> pattern will then skip forward to that point if backtracked into on failure. Any number of C<(*MARK)> patterns are allowed, and the I portion may be duplicated. =end original このゼロ幅のマッチングはパターン内の特定の箇所がマッチングに成功したときに、 文字列の中で達した位置を記録するために使われます。 このマークには名前をつけることもできます。 後者の C<(*SKIP)> パターンは失敗時でバックトラックしたときにその箇所まで スキップします。 C<(*MARK)> パターンはいくつでも使うことができて、I 部分は 重複することもあります。 =begin original In addition to interacting with the C<(*SKIP)> pattern, C<(*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. =end original C<(*SKIP)> パターンとの相互動作に加えて、C<(*MARK:NAME)> はパターン分岐の 「ラベル」としても使うことができます; このためマッチングの後で、プログラムは そのマッチングにおいてパターンのどの分岐が使われたのかを知ることができます。 =begin original When a match is successful, the C<$REGMARK> variable will be set to the name of the most recently executed C<(*MARK:NAME)> that was involved in the match. =end original マッチングの成功時に、C<$REGMARK> 変数はマッチングの中で一番最近に 実行された C<(*MARK:NAME)> の名前を設定します。 =begin original 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 C as efficiently as something like C. =end original これは書く分岐で別々の捕捉グループを使うことなしにパターンのどの分岐が マッチングしたのかを知るために使うことができます; これは perl は C を C 程度に 効率的には最適化できないためパフォーマンスの向上をもたらします。 =begin original 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 C<$REGERROR> variable will be set to the name of the most recently executed C<(*MARK:NAME)>. =end original マッチングが失敗して、そして他の記号がマッチングの失敗で行われずかつ名前を 持っているというのでなければ、C<$REGERROR> 変数には一番最近に実行された 名前が設定されます。 =begin original See L for more details. =end original 詳細は L を参照してください。 =begin original As a shortcut C<(*MARK:NAME)> can be written C<(*:NAME)>. =end original C<(*MARK:NAME)> の短縮形として C<(*:NAME)> とも記述できます。 =item C<(*THEN)> C<(*THEN:NAME)> =begin original This is similar to the "cut group" operator C<::> from Perl 6. Like C<(*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 C<(?(condition)yes-pattern|no-pattern)> do not count as an alternation, as far as C<(*THEN)> is concerned. =end original これは Perl 6 の "cut group" 演算子 C<::> と似ています。 C<(*PRUNE)> のように、この記号は常にマッチングし、そして失敗で バックトラックした時に正規表現エンジンに、代替のある一番内側で閉じている グループ(キャプチャでもそうでなくとも)で次の代替を試みるようにさせます。 C<(*THEN)> が有効である限り、 C<(?(condition)yes-pattern|no-pattern)> の二つの枝は代替とは扱われません。 =begin original Its name comes from the observation that this operation combined with the alternation operator (C<"|">) can be used to create what is essentially a pattern-based if/then/else block: =end original この名前は代替演算子 (C<"|">) と連結されたこの演算子で本質的にパターンベースの if/then/else ブロックとなるものを作るために使うことが できることからきています: ( COND (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ ) =begin original Note that if this operator is used and NOT inside of an alternation then it acts exactly like the C<(*PRUNE)> operator. =end original この演算子が使われていてそしてそれが代替の内側ではなければ これはちょうど C<(*PRUNE)> 演算子のように動作します。 / A (*PRUNE) B / =begin original is the same as =end original は次と同じです / A (*THEN) B / =begin original but =end original しかし / ( A (*THEN) B | C ) / =begin original is not the same as =end original は次と同じではありません / ( A (*PRUNE) B | C ) / =begin original as after matching the I but failing on the I the C<(*THEN)> verb will backtrack and try I; but the C<(*PRUNE)> verb will simply fail. =end original I にマッチングしたけれど I に失敗した後 C<(*THEN)> 記号は バックトラックして I を試みます; しかし C<(*PRUNE)> 記号であれば 単純に失敗します。 =item C<(*COMMIT)> C<(*COMMIT:args)> X<(*COMMIT)> =begin original This is the Perl 6 "commit pattern" C<< >> or C<:::>. It's a zero-width pattern similar to C<(*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, =end original これは Perl 6 の"コミットパターン" C<< >> または C<:::> です。 これは C<(*SKIP)> と似たゼロ幅のパターンですが、失敗でバックトラックした 際にマッチングがすぐに失敗する点で異なります。 それ以降で開始位置を進めて有効なマッチングを探す試行は行われません。 例えば、 'aaabaaab' =~ /a+b?(*COMMIT)(?{print "$&\n"; $count++})(*FAIL)/; print "Count=$count\n"; =begin original outputs =end original これの出力は aaab Count=1 =begin original In other words, once the C<(*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. =end original 言い換えると、いったん C<(*COMMIT)> に入った後に、そのパターンが マッチングしなかったのなら、正規表現エンジンは文字列の残りに対して それ以上のマッチングを試みません。 =item C<(*FAIL)> C<(*F)> C<(*FAIL:arg)> X<(*FAIL)> X<(*F)> =begin original This pattern matches nothing and always fails. It can be used to force the engine to backtrack. It is equivalent to C<(?!)>, but easier to read. In fact, C<(?!)> gets optimised into C<(*FAIL)> internally. You can provide an argument so that if the match fails because of this C directive the argument can be obtained from C<$REGERROR>. =end original このパターンは何にもマッチングせず常に失敗します。 これはエンジンを強制的にバックトラックさせるために使えます。 これは C<(?!)> と等価ですが、より読みやすくなっています。 実際、C<(?!)> は内部的には C<(*FAIL)> に最適化されます。 この C 指示子によってマッチングが失敗したときに C<$REGERROR> から得られる、引数を指定できます。 =begin original It is probably useful only when combined with C<(?{})> or C<(??{})>. =end original これはおそらく C<(?{})> または C<(??{})> と組み合わせた時にだけ 役に立つでしょう。 =item C<(*ACCEPT)> C<(*ACCEPT:arg)> X<(*ACCEPT)> =begin original This pattern matches nothing and causes the end of successful matching at the point at which the C<(*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 C<(??{})>, only the innermost pattern is ended immediately. =end original このパターンマッチングは何もせず C<(*ACCEPT)> パターンと遭遇した場所で 文字列の中で実際にもっとマッチングするものがあるかどうかにかかわらず 成功のマッチングを終了させます。 再帰、または C<(??{})> といったネストしたパターンの内側では、一番内側の パターンのみがすぐに終了します。 =begin original If the C<(*ACCEPT)> is inside of capturing groups then the groups are marked as ended at the point at which the C<(*ACCEPT)> was encountered. For instance: =end original C<(*ACCEPT)> が捕捉グループの内側で使われた場合捕捉グループは C<(*ACCEPT)> と遭遇した位置で終了とマークされます。 例えば: 'AB' =~ /(A (A|B(*ACCEPT)|C) D)(E)/x; =begin original will match, and C<$1> will be C and C<$2> will be C<"B">, C<$3> will not be set. If another branch in the inner parentheses was matched, such as in the string 'ACDE', then the C<"D"> and C<"E"> would have to be matched as well. =end original はマッチングし、C<$1> は C になり、C<$2> は C<"B"> に、そして C<$3> は設定されません。 'ACDE' のようにかっこの内側で他の分岐がマッチングしたのなら、 C<"D"> と C<"E"> もマッチングします。 =begin original You can provide an argument, which will be available in the var C<$REGMARK> after the match completes. =end original マッチングが成功した後に C<$REGMARK> 変数で利用可能な引数を指定できます。 =back =back =head2 Warning on C<\1> Instead of C<$1> (C<$1> ではなく C<\1> だったときの警告) =begin original Some people get too used to writing things like: =end original 次のように書くことになれている人も中にはいるでしょう: $pattern =~ s/(\W)/\\\1/g; =begin original This is grandfathered (for \1 to \9) for the RHS of a substitute to avoid shocking the B addicts, but it's a dirty habit to get into. That's because in PerlThink, the righthand side of an C is a double-quoted string. C<\1> in the usual double-quoted string means a control-A. The customary Unix meaning of C<\1> is kludged in for C. However, if you get into the habit of doing that, you get yourself into trouble if you then add an C modifier. =end original (\1 から \9 については) B 中毒な人をびっくりさせないための RHS 置換の 祖先ですが、しかしこれは汚らしい癖です。 Perl においては、C の右側はダブルクォートされた文字列と 考えられるためです。 通常のダブルクォートされた文字列の中では C<\1> は control-A を意味します。 C<\1> の Unix での習慣的な意味は C だけのその場しのぎです。 しかしながら、この癖に漬かっていると C 修飾子を使ったときに トラブルとなるでしょう。 s/(\d+)/ \1 + 1 /eg; # causes warning under -w =begin original Or if you try to do =end original または次のようにするかもしれません s/(\d+)/\1000/; =begin original You can't disambiguate that by saying C<\{1}000>, whereas you can fix it with C<${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 I side of the C. =end original これを解消するために C<\{1}000> としないでください; ここでは C<${1}000> とするべきです。 埋め込みの処理は後方参照にマッチングさせる操作より混乱は少ないでしょう。 特に C の I<左> 側では2つの異なった意味になります。 =head2 Repeated Patterns Matching a Zero-length Substring (ゼロ幅の部分文字列にマッチングするパターンの繰り返し) =begin original B: Difficult material (and prose) ahead. This section needs a rewrite. =end original B<警告>: この先には難しい(そして無味乾燥な)内容があります。 このセクションは書き直す必要があるでしょう。 =begin original Regular expressions provide a terse and powerful programming language. As with most other power tools, power comes together with the ability to wreak havoc. =end original 正規表現は簡潔でパワフルなプログラミング言語を提供します。 他の多くの強力なツールとともに、力は破壊の源にもなります。 =begin original A common abuse of this power stems from the ability to make infinite loops using regular expressions, with something as innocuous as: =end original この力のよくある乱用は無害な何かとともに、正規表現使った 無限ループとなります。 'foo' =~ m{ ( o? )* }x; =begin original The C matches at the beginning of "C", and since the position in the string is not moved by the match, C would match again and again because of the C<"*"> quantifier. Another common way to create a similar cycle is with the looping modifier C: =end original C は "C" の始まりにマッチングし、文字列中での位置はこの マッチングでは動かないので、C は C<"*"> 量指定子によって何回も マッチングします。 同じような繰り返しを作るもう一つのよくある形として C 修飾子を使った ループがあります: @matches = ( 'foo' =~ m{ o? }xg ); =begin original or =end original または print "match: <$&>\n" while 'foo' =~ m{ o? }xg; =begin original or the loop implied by C. =end original または C による暗黙のループ。 =begin original 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: =end original しかしながら、長きにわたる経験からいくつかのプログラミングタスクは ゼロ幅の部分文字列に対するマッチングを行う部分式の繰り返しで大幅に 単純にできることがわかりました。 簡単な例を挙げてみます: @chars = split //, $string; # // is not magic in split ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// / =begin original Thus Perl allows such constructs, by I. The rules for this are different for lower-level loops given by the greedy quantifiers C<*+{}>, and for higher-level ones like the C modifier or C operator. =end original このように Perl は I<強制的に無限ループを砕く> ことによってこういった構築を 可能にしています。 このためのルールは貪欲な量指定子 C<*+{}> によって与えられる 低レベルなループとも、C 修飾子や C 演算子による 高レベルなループとも異なります。 =begin original The lower-level loops are I (that is, the loop is broken) when Perl detects that a repeated expression matched a zero-length substring. Thus =end original 低レベルなループは Perl がゼロ幅の部分文字列に対してマッチングする式が 繰り返されたことを検出すると I<中断> されます (つまり、ループは壊されます)。 従って m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x; =begin original is made equivalent to =end original は次と等価にされます m{ (?: NON_ZERO_LENGTH )* (?: ZERO_LENGTH )? }x; =begin original For example, this program =end original 例えば、以下のプログラムは #!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; =begin original prints =end original 以下を表示します hello aaaaa b =begin original Notice that "hello" is only printed once, as when Perl sees that the sixth iteration of the outermost C<(?:)*> matches a zero-length string, it stops the C<"*">. =end original "hello" は一度だけ表示されることに注目して下さい; Perl は 一番外側の C<(?:)*> の 6 回目の繰り返しがゼロ長文字列にマッチングするのを 見るので、C<"*"> を止めます。 =begin original 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 L), and so the I match is chosen if the I match is of zero length. =end original 高レベルのループは各繰り返しの間に最後のマッチングがゼロ幅だったかどうかを 追加で保持しています。 ループを終えるために、ゼロ幅のマッチングの後のマッチングはゼロ幅と なることを拒否します。 この禁則処理はバックトラックと相互に動作し(L 参照)、そして I<ベストな> マッチングがゼロ幅だったのなら I<2 番目にベストな> マッチングが選択されます。 =begin original For example: =end original 例: $_ = 'bar'; s/\w??/<$&>/g; =begin original results in C<< <><><><> >>. At each position of the string the best match given by non-greedy C is the zero-length match, and the I match is what is matched by C<\w>. Thus zero-length matches alternate with one-character-long matches. =end original これは C<< <><><><> >> となります。 文字列の各位置に於いて、貪欲でない C によって得られるベストな マッチングはゼロ幅のマッチングです、 そして I<2 番目にベストな>マッチングは C<\w> によってマッチングするものです。 従ってゼロ幅のマッチングは 1 文字幅のマッチングの代替となります。 =begin original Similarly, for repeated C the second-best match is the match at the position one notch further in the string. =end original 同じように、C の繰り返しでは文字列中の境界一つ遠い位置に 2 番目に ベストなマッチングがマッチングします。 =begin original The additional state of being I is associated with the matched string, and is reset by each assignment to C. Zero-length matches at the end of the previous match are ignored during C. =end original I<ゼロ幅にマッチングしている> という追加の状態はマッチングした文字列に 関連づけられていて、C に対する割り当てによってリセットされます。 前のマッチングの終端でのゼロ幅のマッチングは C の間は無視されます。 =head2 Combining RE Pieces (RE の欠片の結合) =begin original Each of the elementary pieces of regular expressions which were described before (such as C or C<\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 C, C, C I. (in these examples C<"S"> and C<"T"> are regular subexpressions). =end original これまでに説明された (C や C<\Z> といった) 正規表現の基本的な欠片 それぞれは、入力文字列上の与えられた位置で多くとも1つの部分文字列に マッチングします。 しかしながら、典型的な正規表現ではこれらの基本的な欠片は結合演算 C、C、C 等(ここで C<"S"> や C<"T"> は正規表現の部分式)を使って より複雑なパターンへと合成することができます。 =begin original Such combinations can include alternatives, leading to a problem of choice: if we match a regular expression C against C<"abc">, will it match substring C<"a"> or C<"ab">? One way to describe which substring is actually matched is the concept of backtracking (see L). However, this description is too low-level and makes you think in terms of a particular implementation. =end original このような合成には選択の問題を導くために代替を含めることができます: 正規表現 C を C<"abc"> に対してマッチングさせようとしたとき、これは C<"a"> と C<"ab"> のどちらにマッチングするのか? 実際にどちらがマッチングするのかを説明する1つの方法として、 バックトラッキングのコンセプトがあります(L 参照)。 しかしながら、この説明は低レベルすぎて特定の実装を考えなければなりません。 =begin original 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?". =end original もう一つの説明は"より良い"/"より悪い"の考え方で始めます。 与えられた正規表現にマッチングするすべての部分文字列は「最良の」 マッチングから「最悪の」マッチングへとソートすることができます; そして 「最良の」マッチングが選択されます。 これは「どれが選ばれるのか?」という問いかけを「どのマッチングがより良くて、 それがより悪いのか?」という問いかけに置き換えることができます。 =begin original 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 C<"S"> and C<"T"> are regular subexpressions. =end original そして、基本的な要素ではそういった問いかけはありません; なぜならこれらは与えられた位置で可能なマッチングは多くとも1つだからです。 このセクションでは結合演算のより良い/より悪いの考え方で説明していきます。 以下の説明では C<"S"> 及び C<"T"> は正規表現の部分式です。 =over 4 =item C =begin original Consider two possible matches, C and C, C<"A"> and C are substrings which can be matched by C<"S">, C<"B"> and C are substrings which can be matched by C<"T">. =end original 2つの可能なマッチング、C 及び C を考えます; ここで C<"A"> 及び C は C<"S"> にマッチングする部分文字列、 そして C<"B"> 及び C は C<"T"> にマッチングする部分文字列とします。 =begin original If C<"A"> is a better match for C<"S"> than C, C is a better match than C. =end original もし C<"A"> が C<"S"> に対して C よりも良いマッチングであれば、 C は C よりも良いマッチングです。 =begin original If C<"A"> and C coincide: C is a better match than C if C<"B"> is a better match for C<"T"> than C. =end original もし C<"A"> と C が同じであれば: C<"B"> が C<"T"> に対して C よりも 良いマッチングであれば C は C よりも良いマッチングです。 =item C =begin original When C<"S"> can match, it is a better match than when only C<"T"> can match. =end original C<"S"> がマッチングできる時は C<"T"> のみがマッチングするよりも良い マッチングです。 =begin original Ordering of two matches for C<"S"> is the same as for C<"S">. Similar for two matches for C<"T">. =end original C<"S"> に対する2つのマッチングの順序は C<"S"> と同じです。 C<"T"> に対する2つのマッチングも同様です。 =item C =begin original Matches as C (repeated as many times as necessary). =end original C (必要なだけ繰り返し)としてマッチングします。 =item C =begin original Matches as C. =end original C としてマッチングします。 =item C =begin original Matches as C. =end original C としてマッチングします。 =item C, C, C =begin original Same as C, C, C respectively. =end original それぞれ C, C, C と同じです。 =item C, C, C =begin original Same as C, C, C respectively. =end original それぞれ C, C, C と同じです。 =item C<< (?>S) >> =begin original Matches the best match for C<"S"> and only that. =end original C<"S"> の最良のみマッチングします。 =item C<(?=S)>, C<(?<=S)> =begin original Only the best match for C<"S"> is considered. (This is important only if C<"S"> has capturing parentheses, and backreferences are used somewhere else in the whole regular expression.) =end original C<"S"> の最良のマッチングのみが考慮されます。 (これは C<"S"> がキャプチャかっこを持っていて、そして正規表現全体の どこかで後方参照が使われている時のみ重要です.) =item C<(?!S)>, C<(? =begin original For this grouping operator there is no need to describe the ordering, since only whether or not C<"S"> can match is important. =end original このグループ演算子では、C<"S"> がマッチングできるかどうかのみが重要なので、 順序についての説明は必要ありません。 =item C<(??{ EXPR })>, C<(?I)> =begin original The ordering is the same as for the regular expression which is the result of EXPR, or the pattern contained by capture group I. =end original 順序は EXPR の結果の正規表現、または捕捉グループ I に含まれている パターンと同じです。 =item C<(?(condition)yes-pattern|no-pattern)> =begin original Recall that which of C or C actually matches is already determined. The ordering of the matches is the same as for the chosen subexpression. =end original 既に決定している C または C を実際に マッチングさせます。 マッチングの順序は選択された部分式と同じです。 =back =begin original The above recipes describe the ordering of matches I. 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. =end original ここにあげたレシピはI<与えられた位置での>マッチングの順序について 説明しています。 正規表現全体でマッチングがどのように決定されるかを理解するためには もう少しルールが必要です: より若い位置でのマッチングは後ろの方でのマッチングよりもより良いです。 =head2 Creating Custom RE Engines (カスタム RE エンジンの作成) =begin original 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 L for more details. =end original Perl 5.10.0 から、誰でもカスタム正規表現エンジンを作成できます。 これは気弱な人向けではありません; C レベルでプラグインする必要があるからです。 さらなる詳細については L を参照して下さい。 =begin original As an alternative, overloaded constants (see L) provide a simple way to extend the functionality of the RE engine, by substituting one pattern for another. =end original 代替案として、オーバーロードされた定数(L 参照)は あるパターンを別のパターンに置き換えることで、RE エンジンの機能を 拡張する簡単な方法を提供します。 =begin original Suppose that we want to enable a new RE escape-sequence C<\Y|> which matches at a boundary between whitespace characters and non-whitespace characters. Note that C<(?=\S)(? matches exactly at these positions, so we want to have each C<\Y|> in the place of the more complicated version. We can create a module C to do this: =end original 新しい正規表現エスケープシーケンス、空白文字と非空白文字との 境界にマッチングする C<\Y|> を作ってみることにします。 この位置には実際には C<(?=\S)(? がマッチングするので、 この複雑なバージョンを C<\Y|> で置き換えたいとします。 このために C モジュールを作ります: 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)(? enables the new escape in constant regular expressions, I, those without any runtime variable interpolations. As documented in L, this conversion will work only over literal parts of regular expressions. For C<\Y|$re\Y|> the variable part of this regular expression needs to be converted explicitly (but only if the special meaning of C<\Y|> should be enabled inside C<$re>): =end original これで C することで正規表現定数の中で新しいエスケープを 使うことが出来ます; すなわち、これには何の実行時変数の埋め込みもいりません。 L に書かれているように、この変換は正規表現のリテラル部分にのみ 動作します。 C<\Y|$re\Y|> であればこの正規表現の変数部分は明示的に変換する 必要があります(とはいえ C<$re> の中でも C<\Y|> を有効にしたい時のみ)。 use customre; $re = <>; chomp $re; $re = customre::convert $re; /\Y|$re\Y|/; =head2 Embedded Code Execution Frequency (組み込みコードの実行頻度) =begin original The exact rules for how often C<(??{})> and C<(?{})> are executed in a pattern are unspecified. 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. =end original パターン中で C<(??{})> と C<(?{})> がどれくらいの頻度で実行されるかの 正確な規則は未規定です。 マッチングが成功した場合、それらは DWIM を行い、 他のメタパターンと同様、 パターンの受け入れられたパスの中で左から右の順序で適切な回数 実行されることを仮定できます。 受け入れられなかったパスとマッチングの失敗がどれくらいパターンの実行回数に 影響を与えるかは明確に非規定で、 パターンにどの最適化が適用できるかに依存し、バージョン毎に 変わる可能性が高いです。 =begin original For instance in =end original 例えば: "aaabcdeeeee"=~/a(?{print "a"})b(?{print "b"})cde/; =begin original 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". =end original 失敗時に "a" や "b" が何回表示されるかは未規定ですが、 マッチングに成功したときに少なくとも 1 回表示されることは仮定でき、 さらに "b" が表示されるとき、その前には少なくとも 1 回 "a" が 表示されることも仮定できます。 =begin original In the case of branching constructs like the following: =end original 次のような分岐構文の場合: /a(b|(?{ print "a" }))c(?{ print "c" })/; =begin original you can assume that the input "ac" will output "ac", and that "abc" will output only "c". =end original 入力が "ac" なら出力は "ac"、入力が "abc" なら出力は "c" だけと仮定できます。 =begin original When embedded code is quantified, successful matches will call the code once for each matched iteration of the quantifier. For example: =end original 組み込みコードが量指定された場合、マッチングに成功すると 量指定子のそれぞれのマッチングした反復毎に 1 回コードを呼び出します。 例えば: "good" =~ /g(?:o(?{print "o"}))*d/; =begin original will output "o" twice. =end original これは "o" を 2 回出力します。 =head2 PCRE/Python Support (PCRE/Python サポート) =begin original 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: =end original Perl 5.10.0 時点では Perl は幾つかの Python/PCRE 的な正規表現構文拡張を サポートします。 Perl プログラマはこれらの Perl としての構文を推奨しますが、以下のものも 受理されます: =over 4 =item C<< (?PENAMEEpattern) >> =begin original Define a named capture group. Equivalent to C<< (?pattern) >>. =end original 名前付の捕捉グループの定義。 C<< (?pattern) >> と等価。 =item C<< (?P=NAME) >> =begin original Backreference to a named capture group. Equivalent to C<< \g{NAME} >>. =end original 名前付捕捉グループへの後方参照。 C<< \g{NAME} >> と等価。 =item C<< (?P>NAME) >> =begin original Subroutine call to a named capture group. Equivalent to C<< (?&NAME) >>. =end original 名前付き捕捉グループへの関数呼び出し。 C<< (?&NAME) >> と等価。 =back =head1 BUGS =begin original There are a number of issues with regard to case-insensitive matching in Unicode rules. See C<"i"> under L above. =end original Unicode ルールでの大文字小文字を無視したマッチングには多くの問題が あります。 上述の L の C<"i"> を参照してください。 =begin original 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. =end original この文書は、理解が困難なところから、完全かつ徹底的に不明瞭なところまで さまざまです。 jargon に満ちたとりとめのない散文は幾つかの箇所で理解するのに 難儀ではあるでしょう。 =begin original This document needs a rewrite that separates the tutorial content from the reference content. =end original この文書はリファレンス的な内容からチュートリアル的な内容を分離して 書き直す必要があります。 =head1 SEE ALSO =begin original 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.) =end original Perl のパターンマッチングで使われる文法は、 the Bell Labs Research Unix 8th Edition (Version 8) 正規表現ルーチンで 提供されているものからの派生です。 (コードは実際には Henry Spencer の自由に再配布可能な V8 ルーチンの再実装から (遠く)派生しています)。 L. L. L. L. L. L. L. L. =begin original I by Jeffrey Friedl, published by O'Reilly and Associates. =end original O'Reilly and Associates から出版されている、Jeffrey Friedl による I (詳説 正規表現) =begin meta Translate: 山科 氷魚 (YAMASHINA Hio) (5.10.0) Update: SHIRAKATA Kentaro (5.10.1-) Status: completed =end meta