perlre > 5.16.1 との差分

perlre 5.16.1 と 5.28.0 の差分

11
22=encoding euc-jp
33
44=head1 NAME
55X<regular expression> X<regex> X<regexp>
66
77=begin original
88
99perlre - Perl regular expressions
1010
1111=end original
1212
1313perlre - Perl の正規表現
1414
1515=head1 DESCRIPTION
1616
1717=begin original
1818
1919This page describes the syntax of regular expressions in Perl.
2020
2121=end original
2222
2323このページでは Perl での正規表現の構文について説明します。
2424
2525=begin original
2626
27If you haven't used regular expressions before, a quick-start
27If you haven't used regular expressions before, a tutorial introduction
28introduction is available in L<perlrequick>, and a longer tutorial
28is available in L<perlretut>. If you know just a little about them,
29introduction is available in L<perlretut>.
29a quick-start introduction is available in L<perlrequick>.
3030
3131=end original
3232
33もしこれまでに正規表現を使ったことがないのであれば
33もしこれまでに正規表現を使ったことがないなら
34L<perlrequick> にクイックスタートが、L<perlretut> に
34L<perlretut> にチュートリアルあります。
35長めのチュートリアルがあります。
35正規表現を少しだけ知っているなら、L<perlrequick> に
36クイックスタートがあります。
3637
3738=begin original
3839
39For reference on how regular expressions are used in matching
40Except for L</The Basics> section, this page assumes you are familiar
40operations, plus various examples of the same, see discussions of
41with regular expression basics, like what is a "pattern", what does it
41C<m//>, C<s///>, C<qr//> and C<??> in L<perlop/"Regexp Quote-Like
42look like, and how it is basically used. For a reference on how they
42Operators">.
43are used, plus various examples of the same, see discussions of C<m//>,
44C<s///>, C<qr//> and C<"??"> in L<perlop/"Regexp Quote-Like Operators">.
4345
4446=end original
4547
46正規表現マッチング操作でどように使うやそれに関する様々な例に
48L</The Basics> 節例外として、こページは、「パターン」とは何
49それはどのような見た目のものか、基本的にどのようにして使われるか、といった
50正規表現の基本に親しんでいることを仮定しています。
51それらをどのように使うのかやそれに関する様々な例に
4752関しては、L<perlop/"Regexp Quote-Like Operators"> にある
48C<m//>, C<s///>, C<qr//>, C<??> の説明を参照して下さい。
53C<m//>, C<s///>, C<qr//>, C<"??"> の説明を参照して下さい。
4954
55=begin original
56
57New in v5.22, L<C<use re 'strict'>|re/'strict' mode> applies stricter
58rules than otherwise when compiling regular expression patterns. It can
59find things that, while legal, may not be what you intended.
60
61=end original
62
63v5.22 から、L<C<use re 'strict'>|re/'strict' mode> は、
64正規表現パターンをコンパイルするときにその他よりもより厳しい規則を
65適用します。
66これは、正当ではあるけれども、意図していないかもしれないものを
67見つけることができます。
68
69=head2 The Basics
70X<regular expression, version 8> X<regex, version 8> X<regexp, version 8>
71
72(基本)
73
74=begin original
75
76Regular expressions are strings with the very particular syntax and
77meaning described in this document and auxiliary documents referred to
78by this one. The strings are called "patterns". Patterns are used to
79determine if some other string, called the "target", has (or doesn't
80have) the characteristics specified by the pattern. We call this
81"matching" the target string against the pattern. Usually the match is
82done by having the target be the first operand, and the pattern be the
83second operand, of one of the two binary operators C<=~> and C<!~>,
84listed in L<perlop/Binding Operators>; and the pattern will have been
85converted from an ordinary string by one of the operators in
86L<perlop/"Regexp Quote-Like Operators">, like so:
87
88=end original
89
90正規表現とは、この文書と、この文書で参照される補助文書で記述されている、
91特定の構文と意味を持つ文字列です。
92この文字列は「パターン」と呼ばれます。
93パターンは、「ターゲット」と呼ばれる他の文字列が、パターンで指定された
94特性を持つ(または持たない)かどうかを判別するために使われます。
95これをパターンに対するターゲット文字列の「マッチング」と呼びます。
96通常、マッチングは、L<perlop/Binding Operators> にリストされている
97二つの二項演算子 C<=~> および C<!~> の一つの、ターゲットを
98最初のオペランドにし、パターンを 2 番目のオペランドにすることによって
99行われます;
100そしてパターンは次のように、L<perlop/"Regexp Quote-Like Operators"> の
101演算子の一つによって通常の文字列から変換されています。
102
103 $foo =~ m/abc/
104
105=begin original
106
107This evaluates to true if and only if the string in the variable C<$foo>
108contains somewhere in it, the sequence of characters "a", "b", then "c".
109(The C<=~ m>, or match operator, is described in
110L<perlop/m/PATTERN/msixpodualngc>.)
111
112=end original
113
114これは、変数 C<$foo> 内の文字列のどこかに文字並び "a", "b", "c" が
115含まれている場合にのみ真と評価されます。
116(マッチング演算子 C<=~ m> は、L<perlop/m/PATTERN/msixpodualngc> で
117説明されています。)
118
119=begin original
120
121Patterns that aren't already stored in some variable must be delimitted,
122at both ends, by delimitter characters. These are often, as in the
123example above, forward slashes, and the typical way a pattern is written
124in documentation is with those slashes. In most cases, the delimitter
125is the same character, fore and aft, but there are a few cases where a
126character looks like it has a mirror-image mate, where the opening
127version is the beginning delimiter, and the closing one is the ending
128delimiter, like
129
130=end original
131
132何らかの変数にまだ格納されていないパターンは、両端が区切り文字で
133区切られている必要があります。
134これらは上の例のようにスラッシュであることが多く、文書中で
135パターンを記述する一般的な方法はこれらのスラッシュです。
136ほとんどの場合、区切り文字は前と後で同じ文字ですが、文字が鏡像のように
137見える場合がいくつかあります;
138次のように、開くのが開始区切り文字で、閉じるのが終了区切り文字です:
139
140 $foo =~ m<abc>
141
142=begin original
143
144Most times, the pattern is evaluated in double-quotish context, but it
145is possible to choose delimiters to force single-quotish, like
146
147=end original
148
149ほとんどの場合、パターンはダブルクォート風コンテキストで評価されますが、
150次のように区切り文字を選択してシングルクォート風を強制することもできます:
151
152 $foo =~ m'abc'
153
154=begin original
155
156If the pattern contains its delimiter within it, that delimiter must be
157escaped. Prefixing it with a backslash (I<e.g.>, C<"/foo\/bar/">)
158serves this purpose.
159
160=end original
161
162パターン内に区切り文字が含まれている場合は、その区切り文字を
163エスケープする必要があります。
164逆スラッシュを前置すると (例えば、C<"/foo\/bar/">)、この目的を
165達成できます。
166
167=begin original
168
169Any single character in a pattern matches that same character in the
170target string, unless the character is a I<metacharacter> with a special
171meaning described in this document. A sequence of non-metacharacters
172matches the same sequence in the target string, as we saw above with
173C<m/abc/>.
174
175=end original
176
177パターン中のすべての単一の文字は、その文字が個々でまたはこの文書で
178説明されている特別な意味を持った I<メタ文字> である場合以外は、
179ターゲット文字列内の同じ文字にマッチングします。
180非メタ文字の並びは、前述の C<m/abc/> で見たように、
181ターゲット文字列の同じ並びにマッチングします。
182
183=begin original
184
185Only a few characters (all of them being ASCII punctuation characters)
186are metacharacters. The most commonly used one is a dot C<".">, which
187normally matches almost any character (including a dot itself).
188
189=end original
190
191ほんのいくつかの文字 (全て ASCII の句読点文字) がメタ文字です。
192もっとも一般的に使われるものはドット C<"."> で、これは通常
193(ドット自身を含む) ほとんどの文字にマッチングします。
194
195=begin original
196
197You can cause characters that normally function as metacharacters to be
198interpreted literally by prefixing them with a C<"\">, just like the
199pattern's delimiter must be escaped if it also occurs within the
200pattern. Thus, C<"\."> matches just a literal dot, C<"."> instead of
201its normal meaning. This means that the backslash is also a
202metacharacter, so C<"\\"> matches a single C<"\">. And a sequence that
203contains an escaped metacharacter matches the same sequence (but without
204the escape) in the target string. So, the pattern C</blur\\fl/> would
205match any target string that contains the sequence C<"blur\fl">.
206
207=end original
208
209文字は C<"\"> で前置されることで通常はメタ文字としての機能を持っている文字を
210リテラルとして処理させられるようになります;
211パターンの区切り文字がパターンの中に現れる場合は
212エスケープされなければならないのと同様です。
213従って、C<"\."> は、通常の意味ではなく、
214単にリテラルなドット C<"."> にマッチングするようになります。
215つまり、逆スラッシュもメタ文字なので、
216"\\" は単一の C<"\"> にマッチングするということです。
217エスケープされたメタ文字を含む並びは、ターゲット文字列の中の
218同じ並び(但しエスケープなし)にマッチングします。
219それで、パターン C</blur\\fl/> は
220並び C<"blur\fl"> を含むターゲット文字列にマッチングします。
221
222=begin original
223
224The metacharacter C<"|"> is used to match one thing or another. Thus
225
226=end original
227
228メタ文字 C<"|"> は二つのもののどちらかをマッチングするのに使われます。
229従って:
230
231 $foo =~ m/this|that/
232
233=begin original
234
235is TRUE if and only if C<$foo> contains either the sequence C<"this"> or
236the sequence C<"that">. Like all metacharacters, prefixing the C<"|">
237with a backslash makes it match the plain punctuation character; in its
238case, the VERTICAL LINE.
239
240=end original
241
242これは C<$foo> に並び C<"this"> または並び C<"that"> のどちらかが
243含まれている場合にのみ真になります。
244全てのメタ文字と同様、C<"|"> に逆スラッシュを前置すると普通の句読点文字、
245この場合は VERTICAL LINE にマッチングします。
246
247 $foo =~ m/this\|that/
248
249=begin original
250
251is TRUE if and only if C<$foo> contains the sequence C<"this|that">.
252
253=end original
254
255これは、C<$foo> に C<"this|that"> という並びを含んでいる場合にのみ
256真になります。
257
258=begin original
259
260You aren't limited to just a single C<"|">.
261
262=end original
263
264単一の C<"|"> だけに制限されません。
265
266 $foo =~ m/fee|fie|foe|fum/
267
268=begin original
269
270is TRUE if and only if C<$foo> contains any of those 4 sequences from
271the children's story "Jack and the Beanstalk".
272
273=end original
274
275これは、C<$foo> に童話「ジャックとまめの木」から取った
276四つの並びのいずれがを含んでいる場合にのみ真になります。
277
278=begin original
279
280As you can see, the C<"|"> binds less tightly than a sequence of
281ordinary characters. We can override this by using the grouping
282metacharacters, the parentheses C<"("> and C<")">.
283
284=end original
285
286ここで見られるように、C<"|"> は通常の文字の並びより弱く結びつけます。
287これはグループ化メタ文字であるかっこ C<"("> と C<")"> を使って
288上書きできます。
289
290 $foo =~ m/th(is|at) thing/
291
292=begin original
293
294is TRUE if and only if C<$foo> contains either the sequence S<C<"this
295thing">> or the sequence S<C<"that thing">>. The portions of the string
296that match the portions of the pattern enclosed in parentheses are
297normally made available separately for use later in the pattern,
298substitution, or program. This is called "capturing", and it can get
299complicated. See L</Capture groups>.
300
301=end original
302
303これは C<$foo> に並び S<C<"this thing">> または並び
304S<C<"that thing">> のいずれかが含まれている場合にのみ TRUE が返されます。
305かっこで囲まれたパターンの部分と一致する文字列の部分は、通常、後でパターン、
306置換、プログラムで使用するために個別に使用できます。
307これは「捕捉」(capturing)と呼ばれ、複雑になる場合があります。
308L</Capture groups> を参照してください。
309
310=begin original
311
312The first alternative includes everything from the last pattern
313delimiter (C<"(">, C<"(?:"> (described later), I<etc>. or the beginning
314of the pattern) up to the first C<"|">, and the last alternative
315contains everything from the last C<"|"> to the next closing pattern
316delimiter. That's why it's common practice to include alternatives in
317parentheses: to minimize confusion about where they start and end.
318
319=end original
320
321最初の代替には最後のパターン区切り (C<"(">, C<"(?:"> (後述) など、または
322パターンの始まり)から最初の C<"|"> までのすべてが含まれ、
323最後の代替には最後の C<"|"> から次の閉じパターン区切りまでが含まれます。
324通常代替をかっこの中に入れるのは、その開始位置と終了位置が少しはわかりやすく
325なるようにです。
326
327=begin original
328
329Alternatives are tried from left to right, so the first
330alternative found for which the entire expression matches, is the one that
331is chosen. This means that alternatives are not necessarily greedy. For
332example: when matching C<foo|foot> against C<"barefoot">, only the C<"foo">
333part will match, as that is the first alternative tried, and it successfully
334matches the target string. (This might not seem important, but it is
335important when you are capturing matched text using parentheses.)
336
337=end original
338
339代替は左から右へと試されます、なので最初の代替がその完全な式で
340マッチングしたのならそれが選択されます。
341これは代替は貪欲である必要はないということを意味します。
342例えば: C<"barefoot"> に対して C<foo|foot> をマッチングさせると、
343最初の代替から試されるので、C<"foo"> の部分がマッチングし、
344これは対象の文字列に対して成功でマッチングします。
345(これは重要ではないでしょうが、かっこを使ってマッチングしたテキストを
346捕捉しているときには重要でしょう。)
347
348=begin original
349
350Besides taking away the special meaning of a metacharacter, a prefixed
351backslash changes some letter and digit characters away from matching
352just themselves to instead have special meaning. These are called
353"escape sequences", and all such are described in L<perlrebackslash>. A
354backslash sequence (of a letter or digit) that doesn't currently have
355special meaning to Perl will raise a warning if warnings are enabled,
356as those are reserved for potential future use.
357
358=end original
359
360接頭辞付き逆スラッシュは、メタ文字の特殊な意味を取り除くだけでなく、
361一部の文字や数字をそれ自体と一致させないように変更し、
362代わりに特殊な意味を持つようにします。
363これらは「エスケープシーケンス」と呼ばれ、L<perlrebackslash> で
364説明されています。
365現在 Perl にとって特殊な意味を持たない (文字や数字の)
366逆スラッシュシーケンスは、警告が有効になっている場合に警告を発します;
367これらは将来使用するために予約されているためです。
368
369=begin original
370
371One such sequence is C<\b>, which matches a boundary of some sort.
372C<\b{wb}> and a few others give specialized types of boundaries.
373(They are all described in detail starting at
374L<perlrebackslash/\b{}, \b, \B{}, \B>.) Note that these don't match
375characters, but the zero-width spaces between characters. They are an
376example of a L<zero-width assertion|/Assertions>. Consider again,
377
378=end original
379
380そのようなシーケンスのひとつは C<\b> です;
381これはある種の境界にマッチします。
382C<\b{wb}> やその他のいくつかは特定の境界を与えます。
383(これらはすべて L<perlrebackslash/\b{}, \b, \B{}, \B> で詳細に
384記述されています。)
385これらは文字ではなく、文字と文字の間のゼロ幅の
386スペースにマッチングすることに注意してください。
387これらは L<ゼロ幅言明|/Assertions> の例です。
388もう一度考えてみます:
389
390 $foo =~ m/fee|fie|foe|fum/
391
392=begin original
393
394It evaluates to TRUE if, besides those 4 words, any of the sequences
395"feed", "field", "Defoe", "fume", and many others are in C<$foo>. By
396judicious use of C<\b> (or better (because it is designed to handle
397natural language) C<\b{wb}>), we can make sure that only the Giant's
398words are matched:
399
400=end original
401
402これは、これら四つの単語以外に、"feed", "field", "Defoe", "fume",
403その他多くのシーケンスのいずれかが C<$foo> にある場合、TRUE と評価されます。
404C<\b>(または(自然言語を処理するように設計されているため) より良い
405C<\b{wb}>)を慎重に使用することで、
406確実に巨人の単語だけが一致するようにできます。
407
408 $foo =~ m/\b(fee|fie|foe|fum)\b/
409 $foo =~ m/\b{wb}(fee|fie|foe|fum)\b{wb}/
410
411=begin original
412
413The final example shows that the characters C<"{"> and C<"}"> are
414metacharacters.
415
416=end original
417
418最後の例は、文字 C<"{"> と C<"}"> がメタ文字であることを示しています。
419
420=begin original
421
422Another use for escape sequences is to specify characters that cannot
423(or which you prefer not to) be written literally. These are described
424in detail in L<perlrebackslash/Character Escapes>, but the next three
425paragraphs briefly describe some of them.
426
427=end original
428
429エスケープシーケンスのもう一つの使用法は、文字通りに書くことができない
430(あるいは書きたくない)文字を指定することです。
431これらについては
432L<perlrebackslash/Character Escapes> で詳しく説明していますが、
433次の三つの段落でその一部を簡単に説明します。
434
435=begin original
436
437Various control characters can be written in C language style: C<"\n">
438matches a newline, C<"\t"> a tab, C<"\r"> a carriage return, C<"\f"> a
439form feed, I<etc>.
440
441=end original
442
443様々な制御文字は C 言語形式で書くことができます:
444"\n" は改行にマッチングし、C<"\t"> はタブに、C<"\r"> は復帰に、
445C<"\f"> はフォームフィードにといった具合にマッチングします。
446
447=begin original
448
449More generally, C<\I<nnn>>, where I<nnn> is a string of three octal
450digits, matches the character whose native code point is I<nnn>. You
451can easily run into trouble if you don't have exactly three digits. So
452always use three, or since Perl 5.14, you can use C<\o{...}> to specify
453any number of octal digits.
454
455=end original
456
457より一般的に、C<\I<nnn>> (I<nnn> は 3 桁の 8 進数字) は
458ネイティブな符号位置が I<nnn> の文字にマッチングします。
459正確に 3 桁以外の数字を使うと、簡単に困難に陥ります。
460従って、常に 3 桁で使うか、Perl 5.14 以降なら、
461任意の桁の 8 進数を使うために C<\o{...}> を使えます。
462
463=begin original
464
465Similarly, C<\xI<nn>>, where I<nn> are hexadecimal digits, matches the
466character whose native ordinal is I<nn>. Again, not using exactly two
467digits is a recipe for disaster, but you can use C<\x{...}> to specify
468any number of hex digits.
469
470=end original
471
472同じように、\xI<nn> (I<nn> は16進数字) はネイティブな数値で I<nn> に
473なる文字にマッチングします。
474再び、正確に 2 桁以外の数字を使うのは災いの元ですが、
475任意の桁の 16 進数を指定するために C<\x{...}> を使えます。
476
477=begin original
478
479Besides being a metacharacter, the C<"."> is an example of a "character
480class", something that can match any single character of a given set of
481them. In its case, the set is just about all possible characters. Perl
482predefines several character classes besides the C<".">; there is a
483separate reference page about just these, L<perlrecharclass>.
484
485=end original
486
487メタ文字であることに加えて、C<"."> は、特定の集合の任意の 1 文字に
488マッチングする「文字クラス」の例です。
489この場合、集合ははほぼすべての可能な文字です。
490Perlは C<"."> 以外にもいくつかの文字クラスを事前定義しています;
491これらについては、L<perlrecharclass> という別のリファレンスページが
492あります。
493
494=begin original
495
496You can define your own custom character classes, by putting into your
497pattern in the appropriate place(s), a list of all the characters you
498want in the set. You do this by enclosing the list within C<[]> bracket
499characters. These are called "bracketed character classes" when we are
500being precise, but often the word "bracketed" is dropped. (Dropping it
501usually doesn't cause confusion.) This means that the C<"["> character
502is another metacharacter. It doesn't match anything just by itself; it
503is used only to tell Perl that what follows it is a bracketed character
504class. If you want to match a literal left square bracket, you must
505escape it, like C<"\[">. The matching C<"]"> is also a metacharacter;
506again it doesn't match anything by itself, but just marks the end of
507your custom class to Perl. It is an example of a "sometimes
508metacharacter". It isn't a metacharacter if there is no corresponding
509C<"[">, and matches its literal self:
510
511=end original
512
513独自のカスタム文字クラスを定義するには、パターン内の適切な場所に、集合内に
514必要なすべての文字のリストを配置します。
515これを行うには、リストを C<[]> 大かっこ文字で囲みます。
516これらは、正確にであれば「大かっこ文字クラス」と呼ばれますが、
517「大かっこ」という単語が削除されることがよくあります。
518(通常は、これを削除しても混乱は生じません。)
519これは、C<"["> 文字はもう一つのメタ文字であることを意味します。
520これ自身だけでは何にもマッチングしません;
521Perl に対して、後に続くものが大かっこ文字クラスであることを
522伝えるためにのみ使用されます。
523リテラルの左大かっこにマッチさせたい場合は、C<"\["> のように
524エスケープする必要があります。
525一致する C<"]"> もメタ文字です;
526ここでも何にもマッチしませんが、カスタムクラスの終わりを Perl に
527マークするだけです。
528これは「時々メタ文字」の例です。
529対応する C<"["> が存在しない場合はメタ文字ではなく、
530リテラルにマッチングします。
531
532 print "]" =~ /]/; # prints 1
533
534=begin original
535
536The list of characters within the character class gives the set of
537characters matched by the class. C<"[abc]"> matches a single "a" or "b"
538or "c". But if the first character after the C<"["> is C<"^">, the
539class instead matches any character not in the list. Within a list, the
540C<"-"> character specifies a range of characters, so that C<a-z>
541represents all characters between "a" and "z", inclusive. If you want
542either C<"-"> or C<"]"> itself to be a member of a class, put it at the
543start of the list (possibly after a C<"^">), or escape it with a
544backslash. C<"-"> is also taken literally when it is at the end of the
545list, just before the closing C<"]">. (The following all specify the
546same class of three characters: C<[-az]>, C<[az-]>, and C<[a\-z]>. All
547are different from C<[a-z]>, which specifies a class containing
548twenty-six characters, even on EBCDIC-based character sets.)
549
550=end original
551
552文字クラスの中の文字のリストは、そのクラスがマッチングする
553文字の集合を表しています。
554C<"[abc]"> は単一の "a" または "b" または "c" にマッチングします。.
555しかし、C<"["> の後の最初の文字が C<"^"> だったときには、その文字クラスは
556リストの中にない任意の文字にマッチングします。
557リストの中では、文字 C<"-"> は文字の範囲を意味します;
558なので C<a-z> は "a" と "z" を含めてそれらの間にあるすべての文字を表します。
559文字クラスの要素として C<"-"> または C<"]"> 自身を使いたい時には、
560リストの先頭に (あるいは C<"^"> の後に) 置くか、逆スラッシュを使って
561エスケープします。
562C<"-"> はリストの終端、リストを閉じる C<"]"> の直前にあったときも
563リテラルとして扱われます。
564(次の例はすべて同じ3文字からなる文字クラスです: C<[-az]>, C<[az-]>,
565C<[a\-z]>。
566これらはすべて EBCDIC ベースの文字集合であっても26文字からなる文字集合
567C<[a-z]> とは異なります。)
568
569=begin original
570
571There is lots more to bracketed character classes; full details are in
572L<perlrecharclass/Bracketed Character Classes>.
573
574=end original
575
576大かっこ文字クラスにはもっと色々な要素があります; 完全な詳細は
577L<perlrecharclass/Bracketed Character Classes> にあります。
578
579=head3 Metacharacters
580X<metacharacter>
581X<\> X<^> X<.> X<$> X<|> X<(> X<()> X<[> X<[]>
582
583(メタ文字)
584
585=begin original
586
587L</The Basics> introduced some of the metacharacters. This section
588gives them all. Most of them have the same meaning as in the I<egrep>
589command.
590
591=end original
592
593L</The Basics> ではメタ文字の一部を導入しました。
594この節ではその全てを示します。
595そのほとんどは I<egrep> コマンドと同じ意味を持ちます。
596
597=begin original
598
599Only the C<"\"> is always a metacharacter. The others are metacharacters
600just sometimes. The following tables lists all of them, summarizes
601their use, and gives the contexts where they are metacharacters.
602Outside those contexts or if prefixed by a C<"\">, they match their
603corresponding punctuation character. In some cases, their meaning
604varies depending on various pattern modifiers that alter the default
605behaviors. See L</Modifiers>.
606
607=end original
608
609C<"\"> のみが常にメタ文字です。
610その他は時々にだけメタ文字です。
611次の表は、すべてのメタ文字の一覧、使用方法の概要、
612メタ文字になるコンテキストを示しています。
613これらのコンテキスト以外では、または C<"\"> で始まる場合は、
614対応する句読点文字とマッチングします。
615場合によっては、既定の動作を変更するさまざまなパターン修飾子によって
616意味が異なります。
617L</Modifiers> を参照してください。
618
619=begin original
620
621 PURPOSE WHERE
622 \ Escape the next character Always, except when
623 escaped by another \
624 ^ Match the beginning of the string Not in []
625 (or line, if /m is used)
626 ^ Complement the [] class At the beginning of []
627 . Match any single character except newline Not in []
628 (under /s, includes newline)
629 $ Match the end of the string Not in [], but can
630 (or before newline at the end of the mean interpolate a
631 string; or before any newline if /m is scalar
632 used)
633 | Alternation Not in []
634 () Grouping Not in []
635 [ Start Bracketed Character class Not in []
636 ] End Bracketed Character class Only in [], and
637 not first
638 * Matches the preceding element 0 or more Not in []
639 times
640 + Matches the preceding element 1 or more Not in []
641 times
642 ? Matches the preceding element 0 or 1 Not in []
643 times
644 { Starts a sequence that gives number(s) Not in []
645 of times the preceding element can be
646 matched
647 { when following certain escape sequences
648 starts a modifier to the meaning of the
649 sequence
650 } End sequence started by {
651 - Indicates a range Only in [] interior
652 # Beginning of comment, extends to line end Only with /x modifier
653
654=end original
655
656 目的 場所
657 \ 次の文字をエスケープ もう一つの \ で
658 エスケープしない限り常に
659 ^ 文字列(または /m が使われていれば行) の [] の中以外
660 先頭にマッチング
661 ^ [] クラスの補集合 [] の先頭
662 . 改行以外の任意の 1 文字にマッチング [] の中以外
663 (/s の下では改行を含む)
664 $ 文字列の末尾にマッチング [] の中以外、しかし
665 (または文字列の最後の改行の前; スカラの変数展開を
666 または /m が使われていれば改行の前) 意味する
667 | 代替 [] の中以外
668 () グループ化 [] の中以外
669 [ 大かっこ文字クラスの開始 [] の中以外
670 ] 大かっこ文字クラスの終了 [] のみで先頭以外
671 * 前にある要素に 0 回以上マッチング [] の中以外
672 + 前にある要素に 1 回以上マッチング [] の中以外
673 ? 前にある要素に 0 回または 1 回マッチング [] の中以外
674 { 前にある要素がマッチングする回数を指定する [] の中以外
675 並びの開始
676 { 以下のいくつかのエスケープシーケンスで
677 シーケンスの意味の修飾子の開始
678 } { で開始した並びの終わり
679 - 範囲を示す [] の内部のみ
680 # コメントの開始; 行末まで /x 修飾子のみ
681
682=begin original
683
684Notice that most of the metacharacters lose their special meaning when
685they occur in a bracketed character class, except C<"^"> has a different
686meaning when it is at the beginning of such a class. And C<"-"> and C<"]">
687are metacharacters only at restricted positions within bracketed
688character classes; while C<"}"> is a metacharacter only when closing a
689special construct started by C<"{">.
690
691=end original
692
693ほとんどのメタ文字は、かっこで囲まれた文字クラス内で出現すると
694特殊な意味を失うことに注意してください;
695ただし、C<"^"> は、そのようなクラスの先頭では異なる意味を持ちます。
696また、C<"-"> と C<"]"> は、かっこ弧で囲まれた文字クラス内の限定された
697位置でだけメタ文字になります;
698一方、C<"}"> は、C<"{"> によって開始された特殊な構造体を
699閉じるときにのみメタ文字です。
700
701=begin original
702
703In double-quotish context, as is usually the case, you need to be
704careful about C<"$"> and the non-metacharacter C<"@">. Those could
705interpolate variables, which may or may not be what you intended.
706
707=end original
708
709ダブルクォート風のコンテキストでは、通常の場合と同様、
710C<"$"> とメタ文字でない C<"@"> に注意する必要があります。
711これらは変数を補完することができますが、それは
712意図したものである場合とない場合があります。
713
714=begin original
715
716These rules were designed for compactness of expression, rather than
717legibility and maintainability. The L</E<sol>x and E<sol>xx> pattern
718modifiers allow you to insert white space to improve readability. And
719use of S<C<L<re 'strict'|re/'strict' mode>>> adds extra checking to
720catch some typos that might silently compile into something unintended.
721
722=end original
723
724これらの規則は、読みやすさや保守性ではなく、表現のコンパクトさを
725考慮して設計されています。
726L</E<sol>x and E<sol>xx> パターン修飾子を使用すると、読みやすさを
727向上させるために空白を挿入できます。
728また、S<C<L<re 'strict'|re/'strict' mode>>> を使用すると、
729意図しないものに暗黙的にコンパイルされる可能性のあるタイプミスを
730捕捉するための追加チェックが追加されます。
731
732=begin original
733
734By default, the C<"^"> character is guaranteed to match only the
735beginning of the string, the C<"$"> character only the end (or before the
736newline at the end), and Perl does certain optimizations with the
737assumption that the string contains only one line. Embedded newlines
738will not be matched by C<"^"> or C<"$">. You may, however, wish to treat a
739string as a multi-line buffer, such that the C<"^"> will match after any
740newline within the string (except if the newline is the last character in
741the string), and C<"$"> will match before any newline. At the
742cost of a little more overhead, you can do this by using the
743L</C<E<sol>m>> modifier on the pattern match operator. (Older programs
744did this by setting C<$*>, but this option was removed in perl 5.10.)
745X<^> X<$> X</m>
746
747=end original
748
749デフォルトでは、文字 C<"^"> は文字列の先頭にのみ、そして文字 C<"$"> は
750末尾(または末尾の改行の前)にのみマッチングすることを保証し、そして Perl は
751文字列が 1 行のみを含んでいるという仮定でいくつかの最適化を行います。
752埋め込まれている改行文字は C<"^"> や C<"$"> とはマッチングしません。
753しかし文字列には複数行が格納されていて、C<"^"> は任意の改行の後(但し
754改行文字が文字列の最後の文字だった場合は除く)、そして C<"$"> は任意の改行の
755前でマッチングさせたいこともあるでしょう。
756小さなオーバーヘッドはありますが、これはパターンマッチングで
757L</C<E<sol>m>> 修飾子を使うことで行うことができます。
758(古いプログラムでは C<$*> を設定することでこれを行っていましたが
759これは perl 5.10 では削除されています。)
760X<^> X<$> X</m>
761
762=begin original
763
764To simplify multi-line substitutions, the C<"."> character never matches a
765newline unless you use the L<C<E<sol>s>|/s> modifier, which in effect tells
766Perl to pretend the string is a single line--even if it isn't.
767X<.> X</s>
768
769=end original
770
771複数行での利用を簡単にするために、文字 C<"."> は L<C<E<sol>s>|/s> 修飾子を
772使って Perl に文字列を 1 行として処理すると Perl に伝えない限り、
773改行にはマッチングしません。
774X<.> X</s>
775
50776=head2 Modifiers
51777
52778(修飾子)
53779
780=head3 Overview
781
782(概要)
783
54784=begin original
55785
56Matching operations can have various modifiers. Modifiers
786The default behavior for matching can be changed, using various
57that relate to the interpretation of the regular expression inside
787modifiers. Modifiers that relate to the interpretation of the pattern
58are listed below. Modifiers that alter the way a regular expression
788are listed just below. Modifiers that alter the way a pattern is used
59is used by Perl are detailed in L<perlop/"Regexp Quote-Like Operators"> and
789by Perl are detailed in L<perlop/"Regexp Quote-Like Operators"> and
60790L<perlop/"Gory details of parsing quoted constructs">.
61791
62792=end original
63793
64マッチング操作には様々な修飾子(modifier)があります。
794マッチングのデフォルトの振る舞い様々な修飾子 (modifier)
65修飾子は正規表現内の解釈に関連する物、次に一覧にしています。
795変更ます。
66Perl が正規表現を使う方法を変更する
796パターンの解釈に関連する修飾子は、直後に一覧にしています。
797Perl がパターンを使う方法を変更する
67798修飾子は L<perlop/"Regexp Quote-Like Operators">
68799及び L<perlop/"Gory details of parsing quoted constructs"> に
69800説明されています。
70801
71802=over 4
72803
73=item m
804=item B<C<m>>
74805X</m> X<regex, multiline> X<regexp, multiline> X<regular expression, multiline>
75806
76807=begin original
77808
78Treat string as multiple lines. That is, change "^" and "$" from matching
809Treat the string being matched against as multiple lines. That is, change C<"^"> and C<"$"> from matching
79the start or end of the string to matching the start or end of any
810the start of the string's first line and the end of its last line to
80line anywhere within the string.
811matching the start and end of each line within the string.
81812
82813=end original
83814
84文字列を複数行として扱います。
815文字列を複数行としてマッチングするように扱います。
85つまり、"^" 及び "$" は文字列の最初最後に対するマッチングから、
816つまり、C<"^"> 及び C<"$"> は文字列の最初の行の先頭および最後の行の末尾に対する
86文字列中の各行の先頭と末尾に対するマッチングへと変更されます。
817マッチングから、文字列中の各行の銭湯と末尾に対するマッチングへと
818変更されます。
87819
88=item s
820=item B<C<s>>
89821X</s> X<regex, single-line> X<regexp, single-line>
90822X<regular expression, single-line>
91823
92824=begin original
93825
94Treat string as single line. That is, change "." to match any character
826Treat the string as single line. That is, change C<"."> to match any character
95827whatsoever, even a newline, which normally it would not match.
96828
97829=end original
98830
99831文字列を 1 行として扱います。
100つまり、"." は任意の 1 文字、通常はマッチングしない改行でさえも
832つまり、C<"."> は任意の 1 文字、通常はマッチングしない改行でさえも
101833マッチングするように変更されます。
102834
103835=begin original
104836
105Used together, as C</ms>, they let the "." match any character whatsoever,
837Used together, as C</ms>, they let the C<"."> match any character whatsoever,
106while still allowing "^" and "$" to match, respectively, just after
838while still allowing C<"^"> and C<"$"> to match, respectively, just after
107839and just before newlines within the string.
108840
109841=end original
110842
111C</ms> として共に使うと、"^" 及び "$" はそれぞれ
843C</ms> として共に使うと、C<"^"> 及び C<"$"> はそれぞれ
112文字列中の改行の直前及び直後のマッチングでありつつ、"." は任意の文字に
844文字列中の改行の直前及び直後のマッチングでありつつ、C<"."> は任意の文字に
113845マッチングするようになります。
114846
115=item i
847=item B<C<i>>
116848X</i> X<regex, case-insensitive> X<regexp, case-insensitive>
117849X<regular expression, case-insensitive>
118850
119851=begin original
120852
121Do case-insensitive pattern matching.
853Do case-insensitive pattern matching. For example, "A" will match "a"
854under C</i>.
122855
123856=end original
124857
125858大文字小文字を区別しないパターンマッチングを行います。
859例えば、C</i> の下では "A" は "a" にマッチングします。
126860
127861=begin original
128862
129863If locale matching rules are in effect, the case map is taken from the
130864current
131865locale for code points less than 255, and from Unicode rules for larger
132866code points. However, matches that would cross the Unicode
133rules/non-Unicode rules boundary (ords 255/256) will not succeed. See
867rules/non-Unicode rules boundary (ords 255/256) will not succeed, unless
134L<perllocale>.
868the locale is a UTF-8 one. See L<perllocale>.
135869
136870=end original
137871
138872ロケールマッチングルールが有効になっている場合、符号位置 255 以下の場合は
139873現在のロケールから取られ、より大きい符号位置では Unicode ルールから
140874取られます。
141875しかし、Unicode ルールと非 Unicode ルールの境界(番号255/256) を
142またぐマッチングは成功しません。
876またぐマッチングは、ロケールが UTF-8 のものでない限り成功しません。
143877L<perllocale> を参照してください。
144878
145879=begin original
146880
147There are a number of Unicode characters that match multiple characters
881There are a number of Unicode characters that match a sequence of
148under C</i>. For example, C<LATIN SMALL LIGATURE FI>
882multiple characters under C</i>. For example,
149should match the sequence C<fi>. Perl is not
883C<LATIN SMALL LIGATURE FI> should match the sequence C<fi>. Perl is not
150884currently able to do this when the multiple characters are in the pattern and
151885are split between groupings, or when one or more are quantified. Thus
152886
153887=end original
154888
155C</i> の基で複数の文字にマッチングする Unicode 文字はたくさんあります。
889C</i> の基で複数の文字の並びにマッチングする Unicode 文字はたくさんあります。
156890例えば、C<LATIN SMALL LIGATURE FI> は並び C<fi> にマッチングするべきです。
157891複数の文字がパターン中にあってグループ化で分割されている場合、または
158892どれかの文字に量指定子が付いている場合、Perl は今のところこれを行えません。
159893従って
160894
161895=begin original
162896
163897 "\N{LATIN SMALL LIGATURE FI}" =~ /fi/i; # Matches
164898 "\N{LATIN SMALL LIGATURE FI}" =~ /[fi][fi]/i; # Doesn't match!
165899 "\N{LATIN SMALL LIGATURE FI}" =~ /fi*/i; # Doesn't match!
166900
167901=end original
168902
169903 "\N{LATIN SMALL LIGATURE FI}" =~ /fi/i; # マッチング
170904 "\N{LATIN SMALL LIGATURE FI}" =~ /[fi][fi]/i; # マッチングしない!
171905 "\N{LATIN SMALL LIGATURE FI}" =~ /fi*/i; # マッチングしない!
172906
173907=begin original
174908
175909 # The below doesn't match, and it isn't clear what $1 and $2 would
176910 # be even if it did!!
177911 "\N{LATIN SMALL LIGATURE FI}" =~ /(f)(i)/i; # Doesn't match!
178912
179913=end original
180914
181915 # 次のものはマッチングしないし、もししたとしても $1 と $2 が何になるか
182916 # はっきりしない!!
183917 "\N{LATIN SMALL LIGATURE FI}" =~ /(f)(i)/i; # マッチングしない!
184918
185919=begin original
186920
187Perl doesn't match multiple characters in an inverted bracketed
921Perl doesn't match multiple characters in a bracketed
188character class, which otherwise could be highly confusing. See
922character class unless the character that maps to them is explicitly
923mentioned, and it doesn't match them at all if the character class is
924inverted, which otherwise could be highly confusing. See
925L<perlrecharclass/Bracketed Character Classes>, and
189926L<perlrecharclass/Negation>.
190927
191928=end original
192929
193Perl は、否定大かっこ文字クラスの複数の文字マッングしません;
930Perl は、明示的にマッングについて言及されていない限り、
931大かっこ文字クラスの複数の文字にはマッチングしません;
932そして文字クラスが否定された場合はそれらには全くマッチングしません;
194933さもなければとても混乱することがあるからです。
934L<perlrecharclass/Bracketed Character Classes> と
195935L<perlrecharclass/Negation> を参照して下さい。
196936
937=item B<C<x>> and B<C<xx>>
938X</x>
939
940(B<C<x>> と B<C<xx>>)
941
197942=begin original
198943
199Another bug involves character classes that match both a sequence of
944Extend your pattern's legibility by permitting whitespace and comments.
200multiple characters, and an initial sub-string of that sequence. For
945Details in L</E<sol>x and E<sol>xx>
201example,
202946
203947=end original
204948
205一つのバグは、複数文字の並びと、並びの最初の部分文字列の両方
949空白やコメントを許可してパターンを読みやすくするように拡張します。
206マッチングする文字クラスよるものです。
950詳細は L</E<sol>x and E<sol>xx> あります。
207例えば:
208951
209 /[s\xDF]/i
952=item B<C<p>>
953X</p> X<regex, preserve> X<regexp, preserve>
210954
211955=begin original
212956
213should match both a single and a double "s", since C<\xDF> (on ASCII
957Preserve the string matched such that C<${^PREMATCH}>, C<${^MATCH}>, and
214platforms) matches "ss". However, this bug
958C<${^POSTMATCH}> are available for use after matching.
215(L<[perl #89774]|https://rt.perl.org/rt3/Ticket/Display.html?id=89774>)
216causes it to only match a single "s", even if the final larger match
217fails, and matching the double "ss" would have succeeded.
218959
219960=end original
220961
221これは "s" 一つ二つの両方にマッチングします; なぜなら
962C<${^PREMATCH}>, C<${^MATCH}>, C<${^POSTMATCH}> いったマッチングされた
222(ASCII プラットフォームでの) C<\xDF> は "ss" にマッチングからです。
963文字列をマッチングの後も使えように維持します。
223しかし、このバグ
224(L<[perl #89774]|https://rt.perl.org/rt3/Ticket/Display.html?id=89774>) は
225例え最後のより大きいマッチングが失敗し、"ss" が成功しても、
226単一の "s2 にのみマッチングするようになります。
227964
228965=begin original
229966
230Also, Perl matching doesn't fully conform to the current Unicode C</i>
967In Perl 5.20 and higher this is ignored. Due to a new copy-on-write
231recommendations, which ask that the matching be made upon the NFD
968mechanism, C<${^PREMATCH}>, C<${^MATCH}>, and C<${^POSTMATCH}> will be available
232(Normalization Form Decomposed) of the text. However, Unicode is
969after the match regardless of the modifier.
233in the process of reconsidering and revising their recommendations.
234970
235971=end original
236972
237また、Perl のマッチングは現在の Unicode の C</i> 勧告に完全に
973Perl 5.20 以降でこれは無視されます。
238準拠ません; テキスの NFD (Normalization Form Decomposed) 対しての
974しいコピーオンライ機構より、
239マッチングに関する部分です。
975C<${^PREMATCH}>, C<${^MATCH}>, and C<${^POSTMATCH}> はこの修飾子に関わらず
240しかし、Unicode は勧告再検討と改訂の作業中です。
976マッチング後も利用可能です。
241977
242=item x
978=item B<C<a>>, B<C<d>>, B<C<l>>, and B<C<u>>
243X</x>
979X</a> X</d> X</l> X</u>
244980
981(B<C<a>>, B<C<d>>, B<C<l>>, B<C<u>>)
982
245983=begin original
246984
247Extend your pattern's legibility by permitting whitespace and comments.
985These modifiers, all new in 5.14, affect which character-set rules
248Details in L</"/x">
986(Unicode, I<etc>.) are used, as described below in
987L</Character set modifiers>.
249988
250989=end original
251990
252空白やコメントを許可てパターンを読みやすくするように拡張します。
9915.14 から導入されたこれらの新い修飾子は、どの文字集合規則
253詳細は L</"/x">あります
992(Unicode など) が使われるか影響を与えます;
993L</Character set modifiers> で後述します。
254994
255=item p
995=item B<C<n>>
256X</p> X<regex, preserve> X<regexp, preserve>
996X</n> X<regex, non-capture> X<regexp, non-capture>
997X<regular expression, non-capture>
257998
258999=begin original
2591000
260Preserve the string matched such that ${^PREMATCH}, ${^MATCH}, and
1001Prevent the grouping metacharacters C<()> from capturing. This modifier,
261${^POSTMATCH} are available for use after matching.
1002new in 5.22, will stop C<$1>, C<$2>, I<etc>... from being filled in.
2621003
2631004=end original
2641005
265${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} とったマッチングされた文字列を
1006グループ化メタ文字 C<()> が捕捉しなようにします。
266マッチング後も使えように維持します。
10075.22 からこの修飾子は、C<$1>, C<$2> などを埋めのを止めます。
2671008
268=item g and c
1009 "hello" =~ /(hi|hello)/; # $1 is "hello"
269X</g> X</c>
1010 "hello" =~ /(hi|hello)/n; # $1 is undef
2701011
271(g と c)
1012=begin original
2721013
1014This is equivalent to putting C<?:> at the beginning of every capturing group:
1015
1016=end original
1017
1018これは各捕捉グループの始めに C<?:> を置くのと等価です:
1019
1020 "hello" =~ /(?:hi|hello)/; # $1 is undef
1021
2731022=begin original
2741023
275Global matching, and keep the Current position after failed matching.
1024C</n> can be negated on a per-group basis. Alternatively, named captures
276Unlike i, m, s and x, these two flags affect the way the regex is used
1025may still be used.
277rather than the regex itself. See
278L<perlretut/"Using regular expressions in Perl"> for further explanation
279of the g and c modifiers.
2801026
2811027=end original
2821028
283ローバ(Global)なマッチング、及びマッチング失敗後の現在置の保持
1029C</n> はグループ単で否定できます
284i, m, s, x とは違い、こ二つのフラグ
1030代わりに、名前付き捕捉まだ使えます。
285正規表現そのものではなく正規表現の使われ方に作用します。
286g 及び c 修飾子の詳細な説明は
287L<perlretut/"Using regular expressions in Perl"> を参照してください。
2881031
289=item a, d, l and u
1032 "hello" =~ /(?-n:(hi|hello))/n; # $1 is "hello"
290X</a> X</d> X</l> X</u>
1033 "hello" =~ /(?<greet>hi|hello)/n; # $1 is "hello", $+{greet} is
1034 # "hello"
2911035
292(a, d, l, u)
1036=item Other Modifiers
2931037
1038(その他の修飾子)
1039
2941040=begin original
2951041
296These modifiers, all new in 5.14, affect which character-set semantics
1042There are a number of flags that can be found at the end of regular
297(Unicode, etc.) are used, as described below in
1043expression constructs that are I<not> generic regular expression flags, but
298L</Character set modifiers>.
1044apply to the operation being performed, like matching or substitution (C<m//>
1045or C<s///> respectively).
2991046
3001047=end original
3011048
3025.14 から導入されたこれらの新しい修飾子は、どの文字集合意味論
1049一般的な正規表現フラグ I<でない> ですがマッチングや置換 (それぞれ C<m//>
303(Unicode など) が使われる影響を与えます;
1050 C<s///>) のような操作実行される適用される
304L</Character set modifiers> で後述します。
1051多くのフラグが正規表現構文の末尾に見つけられます。
3051052
1053=begin original
1054
1055Flags described further in
1056L<perlretut/"Using regular expressions in Perl"> are:
1057
1058=end original
1059
1060L<perlretut/"Using regular expressions in Perl"> に
1061さらに記述されているフラグは:
1062
1063 c - keep the current position during repeated matching
1064 g - globally match the pattern repeatedly in the string
1065
1066=begin original
1067
1068Substitution-specific modifiers described in
1069L<perlop/"s/PATTERN/REPLACEMENT/msixpodualngcer"> are:
1070
1071=end original
1072
1073置換専用の修飾子で
1074L<perlop/"s/PATTERN/REPLACEMENT/msixpodualngcer"> に記述されているのは:
1075
1076 e - evaluate the right-hand side as an expression
1077 ee - evaluate the right side as a string then eval the result
1078 o - pretend to optimize your code, but actually introduce bugs
1079 r - perform non-destructive substitution and return the new value
1080
3061081=back
3071082
3081083=begin original
3091084
3101085Regular expression modifiers are usually written in documentation
311as e.g., "the C</x> modifier", even though the delimiter
1086as I<e.g.>, "the C</x> modifier", even though the delimiter
312in question might not really be a slash. The modifiers C</imsxadlup>
1087in question might not really be a slash. The modifiers C</imnsxadlup>
3131088may also be embedded within the regular expression itself using
3141089the C<(?...)> construct, see L</Extended Patterns> below.
3151090
3161091=end original
3171092
3181093正規表現修飾子は文書中では通常「C</x> 修飾子」のように記述され、
3191094これは区切りが実際にはスラッシュでなくてもそう記述されます。
320また、C</imsxadlup> 修飾子は C<(?...)> 構築子を使って正規表現内に
1095また、C</imnsxadlup> 修飾子は C<(?...)> 構築子を使って正規表現内に
3211096埋め込まれることもあります; 後述する L</Extended Patterns> を
3221097参照してください。
3231098
324=head3 /x
1099=head3 Details on some modifiers
3251100
1101(一部の修飾子の詳細)
1102
3261103=begin original
3271104
328C</x> tells
1105Some of the modifiers require more explanation than given in the
1106L</Overview> above.
1107
1108=end original
1109
1110修飾子の一部は前述の L</Overview> よりもさらなる説明が必要です。
1111
1112=head4 C</x> and C</xx>
1113
1114(C</x> と C</xx>)
1115
1116=begin original
1117
1118A single C</x> tells
3291119the regular expression parser to ignore most whitespace that is neither
330backslashed nor within a character class. You can use this to break up
1120backslashed nor within a bracketed character class. You can use this to
331your regular expression into (slightly) more readable parts. The C<#>
1121break up your regular expression into more readable parts.
332character is also treated as a metacharacter introducing a comment,
1122Also, the C<"#"> character is treated as a metacharacter introducing a
333just as in ordinary Perl code. This also means that if you want real
1123comment that runs up to the pattern's closing delimiter, or to the end
334whitespace or C<#> characters in the pattern (outside a character
1124of the current line if the pattern extends onto the next line. Hence,
335class, where they are unaffected by C</x>), then you'll either have to
1125this is very much like an ordinary Perl code comment. (You can include
1126the closing delimiter within the comment only if you precede it with a
1127backslash, so be careful!)
1128
1129=end original
1130
1131単一の C</x> は、逆スラッシュでエスケープされたり大かっこ文字クラスの
1132中だったりしないほとんどの空白を無視するように正規表現パーサに伝えます。
1133これは正規表現を読みやすく部分に分割するために使えます。
1134また C<"#"> は、パターンの閉じ区切り文字まで、またはパターンが次の行に
1135続く場合は現在の行の末尾までのコメントを開始するメタ文字として扱われます。
1136従って、これは通常の Perl コードのコメントととても似ています。
1137(コメントの中の閉じ区切り文字は、逆スラッシュを前置した場合にのみ
1138含めることができます; 注意してください!)
1139
1140=begin original
1141
1142Use of C</x> means that if you want real
1143whitespace or C<"#"> characters in the pattern (outside a bracketed character
1144class, which is unaffected by C</x>), then you'll either have to
3361145escape them (using backslashes or C<\Q...\E>) or encode them using octal,
337hex, or C<\N{}> escapes. Taken together, these features go a long way towards
1146hex, or C<\N{}> escapes.
338making Perl's regular expressions more readable. Note that you have to
1147It is ineffective to try to continue a comment onto the next line by
339be careful not to include the pattern delimiter in the comment--perl has
1148escaping the C<\n> with a backslash or C<\Q>.
340no way of knowing you did not intend to close the pattern early. See
341the C-comment deletion code in L<perlop>. Also note that anything inside
1150=end original
1151
1152C</x> の使用はまた、(C</x> の影響を受けない大かっこ文字クラス内以外で)
1153パターン中に本当の空白や
1154C<"#"> 文字を使いたい場合は、(逆スラッシュや C<\Q...\E> を使って)
1155エスケープするか、8 進数、16 進数、C<\N{}> エスケープのいずれかで
1156エンコードする必要があると言うことです。
1157C<\n> を逆スラッシュや C<\Q> でエスケープすることで
1158コメントを次の行まで続けようとしても無効です。
1159
1160=begin original
1161
1162You can use L</(?#text)> to create a comment that ends earlier than the
1163end of the current line, but C<text> also can't contain the closing
1164delimiter unless escaped with a backslash.
1165
1166=end original
1167
1168現在の行の末尾より早く修了するコメントを作るために
1169L</(?#text)> が使えますが、やはり C<text> は逆スラッシュで
1170エスケープされない限り閉じ区切り文字を含むことはできません。
1171
1172=begin original
1173
1174A common pitfall is to forget that C<"#"> characters begin a comment under
1175C</x> and are not matched literally. Just keep that in mind when trying
1176to puzzle out why a particular C</x> pattern isn't working as expected.
1177
1178=end original
1179
1180よくある落とし穴は、C<"#"> 文字は C</x> の下ではコメントを始めるので、
1181文字通りにマッチしないことを忘れてしまうことです。
1182特定の C</x> パターンが期待通りに動作しない理由を解明しようとするときには、
1183このことを念頭に置いてください。
1184
1185=begin original
1186
1187Starting in Perl v5.26, if the modifier has a second C<"x"> within it,
1188it does everything that a single C</x> does, but additionally
1189non-backslashed SPACE and TAB characters within bracketed character
1190classes are also generally ignored, and hence can be added to make the
1191classes more readable.
1192
1193=end original
1194
1195Perl v5.26 以降では、修飾子に二つ目の C<"x"> が含まれている場合、
1196一つの C</x> が行うことはすべて行いますが、かっこで囲まれた
1197文字クラス内の逆スラッシュのない SPACE および TAB 文字も一般に無視されます;
1198したがって、クラスをより読みやすくするためにこれらを追加することができます。
1199
1200 / [d-e g-i 3-7]/xx
1201 /[ ! @ " # $ % ^ & * () = ? <> ' ]/xx
1202
1203=begin original
1204
1205may be easier to grasp than the squashed equivalents
1206
1207=end original
1208
1209これは、圧縮された同等物よりも掴みやすいかもしれません:
1210
1211 /[d-eg-i3-7]/
1212 /[!@"#$%^&*()=?<>']/
1213
1214=begin original
1215
1216Taken together, these features go a long way towards
1217making Perl's regular expressions more readable. Here's an example:
1218
1219=end original
1220
1221まとめると、これらの機能は Perl の正規表現をより読みやすくするために
1222大きく役立ちます。
1223以下は例です:
1224
1225 # Delete (most) C comments.
1226 $program =~ s {
1227 /\* # Match the opening delimiter.
1228 .*? # Match a minimal number of characters.
1229 \*/ # Match the closing delimiter.
1230 } []gsx;
1231
1232=begin original
1233
1234Note that anything inside
3421235a C<\Q...\E> stays unaffected by C</x>. And note that C</x> doesn't affect
3431236space interpretation within a single multi-character construct. For
3441237example in C<\x{...}>, regardless of the C</x> modifier, there can be no
3451238spaces. Same for a L<quantifier|/Quantifiers> such as C<{3}> or
346C<{5,}>. Similarly, C<(?:...)> can't have a space between the C<?> and C<:>,
1239C<{5,}>. Similarly, C<(?:...)> can't have a space between the C<"(">,
347but can between the C<(> and C<?>. Within any delimiters for such a
1240C<"?">, and C<":">. Within any delimiters for such a
3481241construct, allowed spaces are not affected by C</x>, and depend on the
3491242construct. For example, C<\x{...}> can't have spaces because hexadecimal
3501243numbers don't have spaces in them. But, Unicode properties can have spaces, so
3511244in C<\p{...}> there can be spaces that follow the Unicode rules, for which see
3521245L<perluniprops/Properties accessible through \p{} and \P{}>.
3531246X</x>
3541247
3551248=end original
3561249
357C</x> は、バックスラッシュでエスケープされたり文字クラス中だったりしない
1250C<\Q...\E> の内側のものは C</x> の影響を受けないことに注意してください。
358ほとんどの空白を無視するように正規表現パーサに伝えます。
359これは正規表現を(少し)読みやすく部分に分割するために使えます。
360また、C<#> は通常の Perl コードと同様コメントを開始するメタ文字として
361扱われます。
362これはまた、(C</x> の影響を受けない文字クラス内以外で)パターン中に本当の空白や
363C<#> 文字を使いたい場合は、(逆スラッシュや C<\Q...\E> を使って)
364エスケープするか、8 進数、16 進数、C<\N{}> エスケープのいずれかで
365エンコードする必要があると言うことです。
366まとめると、これらの機能は Perl の正規表現をより読みやすくするために
367大きく役立ちます。
368コメントにパターン区切りを含まないように注意する必要があります--perl は
369早くパターンを終了したいわけではないと言うことを知る手段がありません。
370L<perlop> の C 型式のコメントを削除するコードを参照してください。
371また、C<\Q...\E> の内側のものは C</x> の影響を受けないことにも
372注意してください。
3731251例えば、C<\x{...}> の内部では、C</x> 修飾子に関わらず、スペースを
3741252含むことはできません。
3751253C<{3}> や C<{5,}> のような L<量指定子|/Quantifiers> も同様です。
376また、C<(?:...)> も C<?> と C<:> の間にスペースを含むことはできませんが、
1254また、C<(?:...)> も
377C<(> C<?> の間に含むことできま
1255C<"(">, C<"?">, C<":"> の間にスペースを含むことできません
3781256このような構文の区切り文字の中では、スペースが許されるかどうかは
3791257C</x> に影響されず、構文自身に影響されます。
3801258例えば、16 進数はスペースを含むことができないので C<\x{...}> はスペースを
3811259含むことができません。
3821260しかし、Unicode 特性はスペースを含むことができるので、
3831261C<\p{...}> は Unicode の規則に従ってスペースを含むことができます;
3841262L<perluniprops/Properties accessible through \p{} and \P{}> を
3851263参照してください。
3861264X</x>
3871265
388=head3 Character set modifiers
1266=begin original
3891267
1268The set of characters that are deemed whitespace are those that Unicode
1269calls "Pattern White Space", namely:
1270
1271=end original
1272
1273空白と見なされる文字の集合は、Unicode が "Pattern White Space" と
1274呼ぶもので、次のものです:
1275
1276 U+0009 CHARACTER TABULATION
1277 U+000A LINE FEED
1278 U+000B LINE TABULATION
1279 U+000C FORM FEED
1280 U+000D CARRIAGE RETURN
1281 U+0020 SPACE
1282 U+0085 NEXT LINE
1283 U+200E LEFT-TO-RIGHT MARK
1284 U+200F RIGHT-TO-LEFT MARK
1285 U+2028 LINE SEPARATOR
1286 U+2029 PARAGRAPH SEPARATOR
1287
1288=head4 Character set modifiers
1289
3901290(文字集合修飾子)
3911291
3921292=begin original
3931293
3941294C</d>, C</u>, C</a>, and C</l>, available starting in 5.14, are called
395the character set modifiers; they affect the character set semantics
1295the character set modifiers; they affect the character set rules
3961296used for the regular expression.
3971297
3981298=end original
3991299
40013005.14 から利用可能な C</d>, C</u>, C</a>, C</l> は文字集合修飾子と呼ばれます;
401これらは正規表現で使われる文字集合の意味論に影響を与えます。
1301これらは正規表現で使われる文字集合規則に影響を与えます。
4021302
4031303=begin original
4041304
4051305The C</d>, C</u>, and C</l> modifiers are not likely to be of much use
4061306to you, and so you need not worry about them very much. They exist for
4071307Perl's internal use, so that complex regular expression data structures
4081308can be automatically serialized and later exactly reconstituted,
4091309including all their nuances. But, since Perl can't keep a secret, and
4101310there may be rare instances where they are useful, they are documented
4111311here.
4121312
4131313=end original
4141314
4151315C</d>, C</u>, C</l> 修飾子はよく使うことはないだろうものなので、
4161316これらについてあまり心配する必要はありません。
4171317これらは Perl の内部仕様のために存在しているので、
4181318複雑な正規表現データ構造は自動的に直列化されて、その後全てのニュアンスを
4191319含めて正確に再構成されます。
4201320
4211321=begin original
4221322
4231323The C</a> modifier, on the other hand, may be useful. Its purpose is to
4241324allow code that is to work mostly on ASCII data to not have to concern
4251325itself with Unicode.
4261326
4271327=end original
4281328
4291329一方、C</a> 修飾子は有用かもしれません。
4301330この目的は、Unicode に関して考慮する必要がないように、コードを
4311331ほとんど ASCII データとして動作するようにすることです。
4321332
4331333=begin original
4341334
4351335Briefly, C</l> sets the character set to that of whatever B<L>ocale is in
4361336effect at the time of the execution of the pattern match.
4371337
4381338=end original
4391339
4401340簡単に言うと、C</l> は、文字集合をパターンマッチングの実行時に有効な
4411341ロケール(B<L>ocale)に設定します。
4421342
4431343=begin original
4441344
4451345C</u> sets the character set to B<U>nicode.
4461346
4471347=end original
4481348
4491349C</u> は文字集合を B<U>nicode に設定します。
4501350
4511351=begin original
4521352
4531353C</a> also sets the character set to Unicode, BUT adds several
4541354restrictions for B<A>SCII-safe matching.
4551355
4561356=end original
4571357
4581358C</a> も文字コードを Unicode に設定しますが、
4591359B<A>SCII セーフなマッチングのためにいくつかの制限を加えます。
4601360
4611361=begin original
4621362
4631363C</d> is the old, problematic, pre-5.14 B<D>efault character set
4641364behavior. Its only use is to force that old behavior.
4651365
4661366=end original
4671367
4681368C</d> は古くて問題のある、5.14 以前のデフォルト(B<D>efault)文字集合の
4691369振る舞いです。
4701370これは古い振る舞いを強制するためだけに使います。
4711371
4721372=begin original
4731373
4741374At any given time, exactly one of these modifiers is in effect. Their
4751375existence allows Perl to keep the originally compiled behavior of a
4761376regular expression, regardless of what rules are in effect when it is
4771377actually executed. And if it is interpolated into a larger regex, the
4781378original's rules continue to apply to it, and only it.
4791379
4801380=end original
4811381
4821382任意のある瞬間において、これらの修飾子の内正確に一つだけが有効になります。
4831383これにより、
4841384それが実際に実行されるときにどの規則が有効かに関わらず、
4851385Perl が元々コンパイルされた正規表現の振る舞いを保存できるようにします。
4861386そしてそれがより大きな正規表現に展開された場合、元の規則だけが
4871387適用され続けます。
4881388
4891389=begin original
4901390
4911391The C</l> and C</u> modifiers are automatically selected for
4921392regular expressions compiled within the scope of various pragmas,
4931393and we recommend that in general, you use those pragmas instead of
4941394specifying these modifiers explicitly. For one thing, the modifiers
4951395affect only pattern matching, and do not extend to even any replacement
496done, whereas using the pragmas give consistent results for all
1396done, whereas using the pragmas gives consistent results for all
4971397appropriate operations within their scopes. For example,
4981398
4991399=end original
5001400
5011401C</l> と C</u> の修飾子は、様々なプラグマのスコープ内でコンパイルされた
5021402正規表現で自動的に選択されます;
5031403一般的にはこれらの修飾子を明示的に使うのではなく、これらのプラグマを
5041404使うことを勧めます。
5051405一例を挙げると、修飾子はパターンマッチングに対してのみ影響を与え、
5061406置換には拡張されないことに注意してください;
5071407いっぽうプラグマを使うと、そのスコープ内の全ての適切な操作について
5081408一貫した結果となります。
5091409例えば:
5101410
5111411 s/foo/\Ubar/il
5121412
5131413=begin original
5141414
5151415will match "foo" using the locale's rules for case-insensitive matching,
5161416but the C</l> does not affect how the C<\U> operates. Most likely you
5171417want both of them to use locale rules. To do this, instead compile the
5181418regular expression within the scope of C<use locale>. This both
519implicitly adds the C</l> and applies locale rules to the C<\U>. The
1419implicitly adds the C</l>, and applies locale rules to the C<\U>. The
520lesson is to C<use locale> and not C</l> explicitly.
1420lesson is to C<use locale>, and not C</l> explicitly.
5211421
5221422=end original
5231423
5241424これは大文字小文字マッチングにロケールの規則を使って "foo" に
5251425マッチングしますが、C</l> は C<\U> がどう処理を行うかに影響を与えません。
5261426あなたはほぼ確実にこれら二つにロケールの規則を使うことを臨むはずです。
5271427これをするためには、代わりに
5281428C<use locale> のスコープ内で正規表現をコンパイルします。
529これらは両方とも暗黙に C</l> を追加し、C<\U> にロケールの規則を適用します。.
1429これらは両方とも暗黙に C</l> を追加し、C<\U> にロケールの規則を適用します。
5301430ここで学ぶべきことは、C<use locale> を使って、明示的に C</l> を
5311431使わないことです。
5321432
5331433=begin original
5341434
5351435Similarly, it would be better to use C<use feature 'unicode_strings'>
5361436instead of,
5371437
5381438=end original
5391439
5401440同様に、Unicode の規則にするには次のようにする代わりに
5411441C<use feature 'unicode_strings'> を使った方が良いです:
5421442
5431443 s/foo/\Lbar/iu
5441444
5451445=begin original
5461446
5471447to get Unicode rules, as the C<\L> in the former (but not necessarily
5481448the latter) would also use Unicode rules.
5491449
5501450=end original
5511451
5521452前者の C<\L> (しかし後者は必要ではないです) も Unicode の規則を
5531453使うからです。
5541454
5551455=begin original
5561456
5571457More detail on each of the modifiers follows. Most likely you don't
5581458need to know this detail for C</l>, C</u>, and C</d>, and can skip ahead
5591459to L<E<sol>a|/E<sol>a (and E<sol>aa)>.
5601460
5611461=end original
5621462
5631463それぞれの修飾子に関するさらなる詳細は後述します。
5641464ほとんど確実にあなたは C</l>, C</u>, C</d> の詳細を知る必要はなく、
5651465L<E<sol>a|/E<sol>a (and E<sol>aa)> まで読み飛ばせます。
5661466
5671467=head4 /l
5681468
5691469=begin original
5701470
5711471means to use the current locale's rules (see L<perllocale>) when pattern
5721472matching. For example, C<\w> will match the "word" characters of that
5731473locale, and C<"/i"> case-insensitive matching will match according to
5741474the locale's case folding rules. The locale used will be the one in
5751475effect at the time of execution of the pattern match. This may not be
5761476the same as the compilation-time locale, and can differ from one match
5771477to another if there is an intervening call of the
5781478L<setlocale() function|perllocale/The setlocale function>.
5791479
5801480=end original
5811481
5821482これはパターンマッチングのときに現在のロケールの規則 (L<perllocale> 参照) を
5831483使うことを意味します。
5841484例えば、C<\w> はこのロケールの「単語」文字にマッチングし、
5851485C<"/i"> の大文字小文字マッチングは、現在のロケールの大文字小文字畳み込み規則に
5861486従ってマッチングします。
5871487使われるロケールはパターンマッチングが実行される時点で有効なものです。
5881488これはコンパイル時のロケールと同じではないかもしれませんし、
5891489L<setlocale() 関数|perllocale/The setlocale function>
5901490の呼び出しが間に入ると、呼び出し毎に異なることもあります。
5911491
5921492=begin original
5931493
594Perl only supports single-byte locales. This means that code points
1494Prior to v5.20, Perl did not support multi-byte locales. Starting then,
595above 255 are treated as Unicode no matter what locale is in effect.
1495UTF-8 locales are supported. No other multi byte locales are ever
1496likely to be supported. However, in all locales, one can have code
1497points above 255 and these will always be treated as Unicode no matter
1498what locale is in effect.
1499
1500=end original
1501
1502v5.20 より前では、Perl は複数バイトロケールに対応していませんでした。
1503v5.20 から、UTF-8 ロケールに対応しました。
1504他の複数バイトロケールに対応することはおそらくありません。
1505しかし、全てのロケールで、255 を越える符号位置を保持することができ、
1506これはどのロケールが有効であるかに関わらず常に
1507Unicode として扱われます。
1508
1509=begin original
1510
5961511Under Unicode rules, there are a few case-insensitive matches that cross
597the 255/256 boundary. These are disallowed under C</l>. For example,
1512the 255/256 boundary. Except for UTF-8 locales in Perls v5.20 and
5980xFF (on ASCII platforms) does not caselessly match the character at
1513later, these are disallowed under C</l>. For example, 0xFF (on ASCII
5990x178, C<LATIN CAPITAL LETTER Y WITH DIAERESIS>, because 0xFF may not be
1514platforms) does not caselessly match the character at 0x178, C<LATIN
600C<LATIN SMALL LETTER Y WITH DIAERESIS> in the current locale, and Perl
1515CAPITAL LETTER Y WITH DIAERESIS>, because 0xFF may not be C<LATIN SMALL
601has no way of knowing if that character even exists in the locale, much
1516LETTER Y WITH DIAERESIS> in the current locale, and Perl has no way of
602less what code point it is.
1517knowing if that character even exists in the locale, much less what code
1518point it is.
6031519
6041520=end original
6051521
606Perl は単一バイトロケールのみに対応します。
607つまり、255 を越える符号位置は、どのロケールが有効であるかに関わらず
608Unicode として扱われるということです。
6091522Unicode の規則の基では、255/256 の境界をまたぐ大文字小文字を無視した
6101523マッチングがいくつかあります。
1524Perl v5.20 以降での UTF-8 ロケールを除いて、
6111525これらは C</l> の基では認められません。
6121526例えば、(ASCII プラットフォームで) 0xFF は 0x178,
6131527C<LATIN CAPITAL LETTER Y WITH DIAERESIS> と大文字小文字を無視した
6141528マッチングをしません; なぜなら 0xFF は現在のロケールでは
6151529C<LATIN SMALL LETTER Y WITH DIAERESIS> ではないかもしれず、Perl は
6161530このロケールでこの文字があるかどうかすら知る方法がなく、ましてや
6171531これがどの符号位置かを知る方法もないからです。
6181532
6191533=begin original
6201534
1535In a UTF-8 locale in v5.20 and later, the only visible difference
1536between locale and non-locale in regular expressions should be tainting
1537(see L<perlsec>).
1538
1539=end original
1540
1541v5.20 以降の UTF-8 ロケールでは、
1542正規表現でのロケールと非ロケールの目に見える唯一の違いは
1543汚染だけのはずです
1544(L<perlsec> 参照)。
1545
1546=begin original
1547
6211548This modifier may be specified to be the default by C<use locale>, but
6221549see L</Which character set modifier is in effect?>.
6231550X</l>
6241551
6251552=end original
6261553
6271554この修飾子は C<use locale> によってデフォルトで設定されますが、
6281555L</Which character set modifier is in effect?> を参照してください。
6291556X</l>
6301557
6311558=head4 /u
6321559
6331560=begin original
6341561
6351562means to use Unicode rules when pattern matching. On ASCII platforms,
6361563this means that the code points between 128 and 255 take on their
6371564Latin-1 (ISO-8859-1) meanings (which are the same as Unicode's).
6381565(Otherwise Perl considers their meanings to be undefined.) Thus,
6391566under this modifier, the ASCII platform effectively becomes a Unicode
6401567platform; and hence, for example, C<\w> will match any of the more than
6411568100_000 word characters in Unicode.
6421569
6431570=end original
6441571
6451572これはパターンマッチングのときに Unicode の規則を使うことを意味します。
6461573ASCII プラットフォームでは、これは符号位置 128 から 255 は
6471574Latin-1 (ISO-8859-1) という意味になります (これは Unicode と同じです)。
6481575(さもなければ Perl はこれらの意味は未定義として扱います。)
6491576従って、この修飾子の基では、ASCII プラットフォームは
6501577事実上 Unicode プラットフォームになります; 従って、
6511578例えば、C<\w> は Unicode の 100,000 以上の単語文字のどれにも
6521579マッチングします。
6531580
6541581=begin original
6551582
6561583Unlike most locales, which are specific to a language and country pair,
6571584Unicode classifies all the characters that are letters I<somewhere> in
6581585the world as
6591586C<\w>. For example, your locale might not think that C<LATIN SMALL
6601587LETTER ETH> is a letter (unless you happen to speak Icelandic), but
6611588Unicode does. Similarly, all the characters that are decimal digits
6621589somewhere in the world will match C<\d>; this is hundreds, not 10,
6631590possible matches. And some of those digits look like some of the 10
6641591ASCII digits, but mean a different number, so a human could easily think
6651592a number is a different quantity than it really is. For example,
6661593C<BENGALI DIGIT FOUR> (U+09EA) looks very much like an
6671594C<ASCII DIGIT EIGHT> (U+0038). And, C<\d+>, may match strings of digits
6681595that are a mixture from different writing systems, creating a security
6691596issue. L<Unicode::UCD/num()> can be used to sort
6701597this out. Or the C</a> modifier can be used to force C<\d> to match
6711598just the ASCII 0 through 9.
6721599
6731600=end original
6741601
6751602特定の言語と国に固有であるほとんどのロケールと異なり、
6761603Unicode は世界の I<どこか> で字(letter)として扱われている全ての
6771604文字(character)を C<\w> に分類します。
6781605例えば、あなたのロケールは (あなたがたまたまアイスランド語を話さない限り)
6791606C<LATIN SMALL LETTER ETH> を字として考えないかもしれません。
6801607同様に、世界のどこかで数字である全ての文字は C<\d> にマッチングします;
6811608これは 10 ではなく 100 のマッチングの可能性があります。
6821609さらにこれらの数字の一部は 10 の ASCII 数字と似ていますが、
6831610異なる数字を意味するため、人間はその数字が実際と異なる量であると
6841611簡単に考えてしまいます。
6851612例えば、 C<BENGALI DIGIT FOUR> (U+09EA) は C<ASCII DIGIT EIGHT> (U+0038) に
6861613とてもよく似ています。
6871614C<\d+> は、異なる記法から混ぜた数字の文字列にマッチングするので、
6881615セキュリティ上の問題を作ります。
6891616これを整理するために L<Unicode::UCD/num()> が使われます。
6901617あるいは C</a> 修飾子は、C<\d> が単に ASCII の 0 から 9 に
6911618マッチングすることを強制するために使えます。
6921619
6931620=begin original
6941621
6951622Also, under this modifier, case-insensitive matching works on the full
6961623set of Unicode
6971624characters. The C<KELVIN SIGN>, for example matches the letters "k" and
6981625"K"; and C<LATIN SMALL LIGATURE FF> matches the sequence "ff", which,
6991626if you're not prepared, might make it look like a hexadecimal constant,
7001627presenting another potential security issue. See
7011628L<http://unicode.org/reports/tr36> for a detailed discussion of Unicode
7021629security issues.
7031630
7041631=end original
7051632
7061633また、この修飾子の基では、大文字小文字を無視したマッチングは Unicode の
7071634完全な集合で動作します。
7081635例えば C<KELVIN SIGN> は "k" と "K" にマッチングします;
7091636C<LATIN SMALL LIGATURE FF> は、準備していなければ 16 進数定数のように
7101637見えるかもしれない並び "ff" にマッチングし、もう一つの潜在的な
7111638セキュリティ問題になります。
7121639Unicode のセキュリティ問題に関する詳細な議論については
7131640L<http://unicode.org/reports/tr36> を参照してください。
7141641
7151642=begin original
7161643
717On the EBCDIC platforms that Perl handles, the native character set is
718equivalent to Latin-1. Thus this modifier changes behavior only when
719the C<"/i"> modifier is also specified, and it turns out it affects only
720two characters, giving them full Unicode semantics: the C<MICRO SIGN>
721will match the Greek capital and small letters C<MU>, otherwise not; and
722the C<LATIN CAPITAL LETTER SHARP S> will match any of C<SS>, C<Ss>,
723C<sS>, and C<ss>, otherwise not.
724
725=end original
726
727Perl が扱える EBCDIC プラットフォームでは、ネイティブな文字集合は
728Latin-1 と等価です。
729従ってこの修飾子は、C<"/i"> 修飾子も指定されたときにのみ
730振る舞いを変え、結果として二つの文字にだけ影響を与え、
731完全な Unicode の意味論を与えます:
732C<MICRO SIGN> はギリシャ語の大文字と小文字の C<MU> にマッチングし、
733それ以外はマッチングしません;
734また C<LATIN CAPITAL LETTER SHARP S> は C<SS>, C<Ss>,
735C<sS>, C<ss> のいずれかにはマッチングし、それ以外にはマッチングしません。
736
737=begin original
738
7391644This modifier may be specified to be the default by C<use feature
7401645'unicode_strings>, C<use locale ':not_characters'>, or
7411646C<L<use 5.012|perlfunc/use VERSION>> (or higher),
7421647but see L</Which character set modifier is in effect?>.
7431648X</u>
7441649
7451650=end original
7461651
7471652この修飾子は C<use feature 'unicode_strings>,
7481653C<use locale ':not_characters'>, C<L<use 5.012|perlfunc/use VERSION>>
7491654(またはそれ以上) によってデフォルトに
7501655設定されますが、L</Which character set modifier is in effect?> を
7511656参照してください。
7521657X</u>
7531658
7541659=head4 /d
7551660
7561661=begin original
7571662
7581663This modifier means to use the "Default" native rules of the platform
7591664except when there is cause to use Unicode rules instead, as follows:
7601665
7611666=end original
7621667
7631668この修飾子は、以下のように Unicode の規則が使われる場合を除いて、
7641669プラットフォームの「デフォルトの」(Default) ネイティブな規則を使うことを
7651670意味します:
7661671
7671672=over 4
7681673
7691674=item 1
7701675
7711676=begin original
7721677
7731678the target string is encoded in UTF-8; or
7741679
7751680=end original
7761681
7771682ターゲット文字列が UTF-8 でエンコードされている; または
7781683
7791684=item 2
7801685
7811686=begin original
7821687
7831688the pattern is encoded in UTF-8; or
7841689
7851690=end original
7861691
7871692パターンが UTF-8 でエンコードされている; または
7881693
7891694=item 3
7901695
7911696=begin original
7921697
7931698the pattern explicitly mentions a code point that is above 255 (say by
7941699C<\x{100}>); or
7951700
7961701=end original
7971702
7981703パターンが、(C<\x{100}> のような形で)255 を超える符号位置に明示的に
7991704言及している; または
8001705
8011706=item 4
8021707
8031708=begin original
8041709
8051710the pattern uses a Unicode name (C<\N{...}>); or
8061711
8071712=end original
8081713
8091714パターンが Unicode 名 (C<\N{...}>) を使っている; または
8101715
8111716=item 5
8121717
8131718=begin original
8141719
815the pattern uses a Unicode property (C<\p{...}>)
1720the pattern uses a Unicode property (C<\p{...}> or C<\P{...}>); or
8161721
8171722=end original
8181723
819パターンが Unicode 特性 (C<\p{...}>) を使っている
1724パターンが Unicode 特性 (C<\p{...}>) や C<\P{...}>) を使っている; または
8201725
1726=item 6
1727
1728=begin original
1729
1730the pattern uses a Unicode break (C<\b{...}> or C<\B{...}>); or
1731
1732=end original
1733
1734パターンが Unicode 単語境界 (C<\b{...}> または C<\B{...}>) を使っている;
1735または
1736
1737=item 7
1738
1739=begin original
1740
1741the pattern uses L</C<(?[ ])>>
1742
1743=end original
1744
1745パターンが L</C<(?[ ])>> を使っている
1746
1747=item 8
1748
1749=begin original
1750
1751the pattern uses L<C<(*script_run: ...)>|/Script Runs>
1752
1753=end original
1754
1755パターンが L<C<(*script_run: ...)>|/Script Runs> を使っている
1756
8211757=back
8221758
8231759=begin original
8241760
8251761Another mnemonic for this modifier is "Depends", as the rules actually
8261762used depend on various things, and as a result you can get unexpected
8271763results. See L<perlunicode/The "Unicode Bug">. The Unicode Bug has
8281764become rather infamous, leading to yet another (printable) name for this
8291765modifier, "Dodgy".
8301766
8311767=end original
8321768
8331769この修飾子のもう一つの記憶法は「依存」(Depends)です; 規則は実際には
8341770様々なことに依存していること、また結果として予想外の
8351771結果になるかもしれないからです。
8361772L<perlunicode/The "Unicode Bug"> を参照してください。
8371773Unicode バグは、悪名高くなり、この修飾子のもう一つの(表示可能な)
8381774名前 "Dodgy" を引き起こしています。
8391775
8401776=begin original
8411777
842On ASCII platforms, the native rules are ASCII, and on EBCDIC platforms
1778Unless the pattern or string are encoded in UTF-8, only ASCII characters
843(at least the ones that Perl handles), they are Latin-1.
1779can match positively.
8441780
8451781=end original
8461782
847ASCII プラットフォムでは、ネイティブな規則は ASCII、(少くとも
1783パタンや文字列が UTF-8エンコードされていい限り、
848Perl が扱う) EBCDIC プラトフォームでは、これは Latin-1 です。
1784ASCII 文字のみが肯定的にマチングします。
8491785
8501786=begin original
8511787
8521788Here are some examples of how that works on an ASCII platform:
8531789
8541790=end original
8551791
8561792以下は ASCII プラットフォームでどのように動作するかの例です:
8571793
8581794 $str = "\xDF"; # $str is not in UTF-8 format.
8591795 $str =~ /^\w/; # No match, as $str isn't in UTF-8 format.
8601796 $str .= "\x{0e0b}"; # Now $str is in UTF-8 format.
8611797 $str =~ /^\w/; # Match! $str is now in UTF-8 format.
8621798 chop $str;
8631799 $str =~ /^\w/; # Still a match! $str remains in UTF-8 format.
8641800
8651801=begin original
8661802
8671803This modifier is automatically selected by default when none of the
8681804others are, so yet another name for it is "Default".
8691805
8701806=end original
8711807
8721808この修飾子は他のものが指定されなかった場合にデフォルトとして自動的に
8731809洗濯されるので、これのもう一つの名前は "Default" です。
8741810
8751811=begin original
8761812
8771813Because of the unexpected behaviors associated with this modifier, you
878probably should only use it to maintain weird backward compatibilities.
1814probably should only explicitly use it to maintain weird backward
1815compatibilities.
8791816
8801817=end original
8811818
8821819この修飾子に関する想定外の振る舞いにより、おそらくおかしな後方互換性を
883維持するためだけにこれを使うべきでしょう。
1820維持するためだけにこれを明示的に使うべきでしょう。
8841821
8851822=head4 /a (and /aa)
8861823
8871824(/a (と /aa))
8881825
8891826=begin original
8901827
891This modifier stands for ASCII-restrict (or ASCII-safe). This modifier,
1828This modifier stands for ASCII-restrict (or ASCII-safe). This modifier
892unlike the others, may be doubled-up to increase its effect.
1829may be doubled-up to increase its effect.
8931830
8941831=end original
8951832
8961833この修飾子は ASCII 制限 (あるいは ASCII セーフ) を意味します。
897この修飾子は、他のものと異なり、2 倍にすることで効果が増します。
1834この修飾子は、2 倍にすることで効果が増します。
8981835
8991836=begin original
9001837
9011838When it appears singly, it causes the sequences C<\d>, C<\s>, C<\w>, and
9021839the Posix character classes to match only in the ASCII range. They thus
9031840revert to their pre-5.6, pre-Unicode meanings. Under C</a>, C<\d>
9041841always means precisely the digits C<"0"> to C<"9">; C<\s> means the five
905characters C<[ \f\n\r\t]>; C<\w> means the 63 characters
1842characters C<[ \f\n\r\t]>, and starting in Perl v5.18, the vertical tab;
1843C<\w> means the 63 characters
9061844C<[A-Za-z0-9_]>; and likewise, all the Posix classes such as
9071845C<[[:print:]]> match only the appropriate ASCII-range characters.
9081846
9091847=end original
9101848
9111849これが単体で使われると、C<\d>, C<\s>, C<\w>, Posix 文字クラスは
9121850ASCII の範囲のみにマッチングするようになります。
9131851従って、これらは 5.6 以前の、Unicode 以前の意味に戻します。
9141852C</a> の基では、C<\d> は常に正確に数字 C<"0"> から C<"9"> を意味します;
915C<\s> は C<[ \f\n\r\t]> の 5 文字を意味します;
1853C<\s> は C<[ \f\n\r\t]> の 5 文字、および Perl v5.18 から垂直タブ、
1854を意味します;
9161855C<\w> は C<[A-Za-z0-9_]> の 63 文字を意味します;
9171856同様に、C<[[:print:]]> のような全ての Posix クラスは
9181857適切な ASCII の範囲の文字にのみマッチングします。
9191858
9201859=begin original
9211860
9221861This modifier is useful for people who only incidentally use Unicode,
9231862and who do not wish to be burdened with its complexities and security
9241863concerns.
9251864
9261865=end original
9271866
9281867この修飾子は、偶然 Unicode を使っている人々で、その複雑さと
9291868セキュリティの問題に関する重荷を背負いたくない人々にとっては有用です。
9301869
9311870=begin original
9321871
9331872With C</a>, one can write C<\d> with confidence that it will only match
9341873ASCII characters, and should the need arise to match beyond ASCII, you
9351874can instead use C<\p{Digit}> (or C<\p{Word}> for C<\w>). There are
9361875similar C<\p{...}> constructs that can match beyond ASCII both white
9371876space (see L<perlrecharclass/Whitespace>), and Posix classes (see
9381877L<perlrecharclass/POSIX Character Classes>). Thus, this modifier
9391878doesn't mean you can't use Unicode, it means that to get Unicode
9401879matching you must explicitly use a construct (C<\p{}>, C<\P{}>) that
9411880signals Unicode.
9421881
9431882=end original
9441883
9451884C</a> を使うと、ASCII 文字だけにマッチングすることに自信を持って
9461885書くことができ、ASCII を超えてマッチングする必要が発生したときには、
9471886代わりに C<\p{Digit}> (または C<\w> として C<\p{Word}>) が使えます。
9481887ASCII を超えたスペース (L<perlrecharclass/Whitespace> を参照してください)
9491888と Posix クラス (L<perlrecharclass/POSIX Character Classes> を
9501889参照してください) の両方にマッチングする似たような C<\p{...}> 構文があります。
9511890従って、この修飾子は Unicode が使えなくなるということではなく、
9521891Unicode のマッチングには明示的に Unicode を意味する構文
9531892(C<\p{}>, C<\P{}>) を使わないといけないということです。
9541893
9551894=begin original
9561895
9571896As you would expect, this modifier causes, for example, C<\D> to mean
9581897the same thing as C<[^0-9]>; in fact, all non-ASCII characters match
9591898C<\D>, C<\S>, and C<\W>. C<\b> still means to match at the boundary
9601899between C<\w> and C<\W>, using the C</a> definitions of them (similarly
9611900for C<\B>).
9621901
9631902=end original
9641903
9651904予想できるとおり、 この修飾子は、例えば、C<\D> を C<[^0-9]> と
9661905同じことにします;
9671906実際、全ての非 ASCII 文字は C<\D>, C<\S>, C<\W> にマッチングします。
9681907C<\b> はまだ C<\w> と C<\W> の境界にマッチングします;
9691908これらのために (C<\B> と同様) C</a> の定義を使います。
9701909
9711910=begin original
9721911
9731912Otherwise, C</a> behaves like the C</u> modifier, in that
974case-insensitive matching uses Unicode semantics; for example, "k" will
1913case-insensitive matching uses Unicode rules; for example, "k" will
9751914match the Unicode C<\N{KELVIN SIGN}> under C</i> matching, and code
9761915points in the Latin1 range, above ASCII will have Unicode rules when it
9771916comes to case-insensitive matching.
9781917
9791918=end original
9801919
9811920さもなければ、C</a> は C</u> 修飾子のように振る舞います;
982大文字小文字を無視したマッチングには Unicode の意味論を使います;
1921大文字小文字を無視したマッチングには Unicode の規則を使います;
9831922例えば、"k" は C</i> の基では C<\N{KELVIN SIGN}> にマッチングし、
9841923ASCII の範囲を超える Latin1 の範囲の符号位置は、大文字小文字を無視した
9851924マッチングで使われる場合は Unicode の規則を使います。
9861925
9871926=begin original
9881927
9891928To forbid ASCII/non-ASCII matches (like "k" with C<\N{KELVIN SIGN}>),
990specify the "a" twice, for example C</aai> or C</aia>. (The first
1929specify the C<"a"> twice, for example C</aai> or C</aia>. (The first
991occurrence of "a" restricts the C<\d>, etc., and the second occurrence
1930occurrence of C<"a"> restricts the C<\d>, I<etc>., and the second occurrence
9921931adds the C</i> restrictions.) But, note that code points outside the
9931932ASCII range will use Unicode rules for C</i> matching, so the modifier
9941933doesn't really restrict things to just ASCII; it just forbids the
9951934intermixing of ASCII and non-ASCII.
9961935
9971936=end original
9981937
9991938("k" と C<\N{KELVIN SIGN}> のような) ASCII/非-ASCII マッチングを禁止するには、
1000C</aai> や C</aia> のように "a" を 2 回指定します。
1939C</aai> や C</aia> のように C<"a"> を 2 回指定します。
1001(最初の "a" は C<\d> などを制限し、2 番目は C</i> の制限を追加します。)
1940(最初の C<"a"> は C<\d> などを制限し、2 番目は C</i> の制限を追加します。)
10021941しかし、 ASCII の範囲外の符号位置は C</i> マッチングに Unicode 規則を
10031942使うので、この修飾子は実際には単に ASCII に制限するものではないことに
10041943注意してください; これは単に ASCII と非 ASCII を混ぜることを禁止します。
10051944
10061945=begin original
10071946
10081947To summarize, this modifier provides protection for applications that
10091948don't wish to be exposed to all of Unicode. Specifying it twice
10101949gives added protection.
10111950
10121951=end original
10131952
10141953まとめると、この修飾子は全ての Unicode に対して曝されることを望んでいない
10151954アプリケーションに対する保護を提供します。
101619552 回指定することで追加の保護を提供します。
10171956
10181957=begin original
10191958
10201959This modifier may be specified to be the default by C<use re '/a'>
10211960or C<use re '/aa'>. If you do so, you may actually have occasion to use
1022the C</u> modifier explictly if there are a few regular expressions
1961the C</u> modifier explicitly if there are a few regular expressions
10231962where you do want full Unicode rules (but even here, it's best if
10241963everything were under feature C<"unicode_strings">, along with the
10251964C<use re '/aa'>). Also see L</Which character set modifier is in
10261965effect?>.
10271966X</a>
10281967X</aa>
10291968
10301969=end original
10311970
10321971この修飾子は C<use re '/a'> または C<use re '/aa'> でデフォルトに
10331972設定されます。
10341973そうすると、もし完全な Unicode 規則を使いたい正規表現がある場合は、
10351974C</u> 修飾子を明示的に使う機会があるかもしれません
10361975(その場合でも、全てが C<"unicode_strings"> の基なら、
10371976C<use re '/aa'> と共にするのが最良です)。
10381977L</Which character set modifier is in effect?> も参照してください。
10391978X</a>
10401979X</aa>
10411980
10421981=head4 Which character set modifier is in effect?
10431982
10441983(どの文字集合修飾子が有効?)
10451984
10461985=begin original
10471986
10481987Which of these modifiers is in effect at any given point in a regular
10491988expression depends on a fairly complex set of interactions. These have
10501989been designed so that in general you don't have to worry about it, but
10511990this section gives the gory details. As
10521991explained below in L</Extended Patterns> it is possible to explicitly
10531992specify modifiers that apply only to portions of a regular expression.
10541993The innermost always has priority over any outer ones, and one applying
10551994to the whole expression has priority over any of the default settings that are
10561995described in the remainder of this section.
10571996
10581997=end original
10591998
10601999ある正規表現のあるポイントでどの修飾子が有効かは、かなり複雑な相互作用に
10612000依存します。
10622001これらは、基本的にはあなたがこれらについて心配しなくて良いように
10632002設計されています。
10642003しかし、この節は詳細を記述します。
10652004L</Extended Patterns> で後述するとおり、正規表現の一部にだけ
10662005適用する修飾子を明示的に指定することが可能です。
10672006一番内側のものは常により外側のものより優先され、式全体に適用されるものは
10682007この節の残りで記述されるデフォルト設定より優先されます。
10692008
10702009=begin original
10712010
10722011The C<L<use re 'E<sol>foo'|re/"'/flags' mode">> pragma can be used to set
10732012default modifiers (including these) for regular expressions compiled
10742013within its scope. This pragma has precedence over the other pragmas
10752014listed below that also change the defaults.
10762015
10772016=end original
10782017
10792018C<L<use re 'E<sol>foo'|re/"'/flags' mode">> プラグマは、
10802019このスコープ内でコンパイルされる正規表現に対して(これらを含む)
10812020デフォルトの修飾子を設定するのに使えます。
10822021このプラグマは、デフォルトを変更する後述するその他のプラグマに優先します。
10832022
10842023=begin original
10852024
10862025Otherwise, C<L<use locale|perllocale>> sets the default modifier to C</l>;
10872026and C<L<use feature 'unicode_strings|feature>>, or
10882027C<L<use 5.012|perlfunc/use VERSION>> (or higher) set the default to
10892028C</u> when not in the same scope as either C<L<use locale|perllocale>>
10902029or C<L<use bytes|bytes>>.
10912030(C<L<use locale ':not_characters'|perllocale/Unicode and UTF-8>> also
10922031sets the default to C</u>, overriding any plain C<use locale>.)
10932032Unlike the mechanisms mentioned above, these
10942033affect operations besides regular expressions pattern matching, and so
10952034give more consistent results with other operators, including using
1096C<\U>, C<\l>, etc. in substitution replacements.
2035C<\U>, C<\l>, I<etc>. in substitution replacements.
10972036
10982037=end original
10992038
11002039さもなければ、C<L<use locale|perllocale>> はデフォルト修飾子を C</l> に
11012040設定します; そして、C<L<use feature 'unicode_strings|feature>> か
11022041C<L<use 5.012|perlfunc/use VERSION>> (またはそれ以上) は、
11032042同じスコープに C<L<use locale|perllocale>> や C<L<use bytes|bytes>> が
11042043なければ、デフォルトを C</u> に設定します。
11052044(C<L<use locale ':not_characters'|perllocale/Unicode and UTF-8>> はまた
11062045デフォルトを C</u> に設定し、普通の C<use locale> を上書きします。)
11072046前述した機構と異なり、これらは正規表現パターンマッチング以外の操作に
11082047影響するので、置換での C<\U>, C<\l> を使うことを含むその他の操作と
11092048より一貫性のある結果になります。
11102049
11112050=begin original
11122051
11132052If none of the above apply, for backwards compatibility reasons, the
11142053C</d> modifier is the one in effect by default. As this can lead to
11152054unexpected results, it is best to specify which other rule set should be
11162055used.
11172056
11182057=end original
11192058
11202059前述のどれも適用されない場合、後方互換性のために、
11212060C</d> 修飾子がデフォルトで有効になります。
11222061これは想定外の結果になることがあるので、
11232062その他の規則集合が使われるように指定するのが最良です。
11242063
11252064=head4 Character set modifier behavior prior to Perl 5.14
11262065
11272066(Perl 5.14 より前の文字集合修飾子の振る舞い)
11282067
11292068=begin original
11302069
11312070Prior to 5.14, there were no explicit modifiers, but C</l> was implied
11322071for regexes compiled within the scope of C<use locale>, and C</d> was
11332072implied otherwise. However, interpolating a regex into a larger regex
11342073would ignore the original compilation in favor of whatever was in effect
11352074at the time of the second compilation. There were a number of
11362075inconsistencies (bugs) with the C</d> modifier, where Unicode rules
11372076would be used when inappropriate, and vice versa. C<\p{}> did not imply
11382077Unicode rules, and neither did all occurrences of C<\N{}>, until 5.12.
11392078
11402079=end original
11412080
114220815.14 より前では、明示的な修飾子はありませんが、
11432082C<use locale> のスコープ内でコンパイルされた正規表現に関しては
11442083C</l> が仮定され、さもなければ C</d> が仮定されます。
11452084しかし、ある正規表現をより大きな正規表現に展開した場合、元のコンパイル時の
11462085状況は、2 回目のコンパイル時点で有効なもので上書きされます。
11472086C</d> 演算子には、不適切なときに Unicode 規則が使われる、あるいはその逆の
11482087多くの非一貫性(バグ)があります。
11492088C<\p{}> および C<\N{}> は 5.12 まで Unicode 規則を仮定していません。
11502089
11512090=head2 Regular Expressions
11522091
11532092(正規表現)
11542093
1155=head3 Metacharacters
1156
1157(メタ文字)
1158
1159=begin original
1160
1161The patterns used in Perl pattern matching evolved from those supplied in
1162the Version 8 regex routines. (The routines are derived
1163(distantly) from Henry Spencer's freely redistributable reimplementation
1164of the V8 routines.) See L<Version 8 Regular Expressions> for
1165details.
1166
1167=end original
1168
1169Perl のパターンマッチングで使われるパターンは Version 8 正規表現ルーチンで
1170提供されているものからの派生です。
1171(このルーチンは Henry Spencer の自由に再配布可能な V8 ルーチンの再実装から
1172(遠く)派生しています)。
1173詳細は L<Version 8 Regular Expressions> を参照してください。
1174
1175=begin original
1176
1177In particular the following metacharacters have their standard I<egrep>-ish
1178meanings:
1179X<metacharacter>
1180X<\> X<^> X<.> X<$> X<|> X<(> X<()> X<[> X<[]>
1181
1182=end original
1183
1184特に以下のメタ文字は標準の I<egrep> 風の意味を持っています:
1185X<metacharacter>
1186X<\> X<^> X<.> X<$> X<|> X<(> X<()> X<[> X<[]>
1187
1188=begin original
1189
1190 \ Quote the next metacharacter
1191 ^ Match the beginning of the line
1192 . Match any character (except newline)
1193 $ Match the end of the line (or before newline at the end)
1194 | Alternation
1195 () Grouping
1196 [] Bracketed Character class
1197
1198=end original
1199
1200 \ 次のメタ文字をエスケープ
1201 ^ 行の先頭にマッチング
1202 . 任意の文字にマッチング(但し改行は除く)
1203 $ 行の終端にマッチング(または終端の改行の前)
1204 | 代替
1205 () グループ化
1206 [] 文字クラス
1207
1208=begin original
1209
1210By default, the "^" character is guaranteed to match only the
1211beginning of the string, the "$" character only the end (or before the
1212newline at the end), and Perl does certain optimizations with the
1213assumption that the string contains only one line. Embedded newlines
1214will not be matched by "^" or "$". You may, however, wish to treat a
1215string as a multi-line buffer, such that the "^" will match after any
1216newline within the string (except if the newline is the last character in
1217the string), and "$" will match before any newline. At the
1218cost of a little more overhead, you can do this by using the /m modifier
1219on the pattern match operator. (Older programs did this by setting C<$*>,
1220but this option was removed in perl 5.9.)
1221X<^> X<$> X</m>
1222
1223=end original
1224
1225デフォルトでは、文字 "^" は文字列の先頭にのみ、そして文字 "$" は
1226末尾(または末尾の改行の前)にのみマッチングすることを保証し、そして Perl は
1227文字列が 1 行のみを含んでいるという仮定でいくつかの最適化を行います。
1228埋め込まれている改行文字は "^" や "$" とはマッチングしません。
1229しかし文字列には複数行が格納されていて、"^" は任意の改行の後(但し
1230改行文字が文字列の最後の文字だった場合は除く)、そして "$" は任意の改行の前で
1231マッチングさせたいこともあるでしょう。
1232小さなオーバーヘッドはありますが、これはパターンマッチングで /m 修飾子を
1233使うことで行うことができます。
1234(古いプログラムでは C<$*> を設定することでこれを行っていましたが
1235これは perl 5.9 では削除されています。)
1236X<^> X<$> X</m>
1237
1238=begin original
1239
1240To simplify multi-line substitutions, the "." character never matches a
1241newline unless you use the C</s> modifier, which in effect tells Perl to pretend
1242the string is a single line--even if it isn't.
1243X<.> X</s>
1244
1245=end original
1246
1247複数行での利用を簡単にするために、文字 "." は C</s> 修飾子を
1248使って Perl に文字列を 1 行として処理すると伝えない限り
1249改行にはマッチングしません。
1250X<.> X</s>
1251
12522094=head3 Quantifiers
12532095
12542096(量指定子)
12552097
12562098=begin original
12572099
1258The following standard quantifiers are recognized:
2100Quantifiers are used when a particular portion of a pattern needs to
2101match a certain number (or numbers) of times. If there isn't a
2102quantifier the number of times to match is exactly one. The following
2103standard quantifiers are recognized:
12592104X<metacharacter> X<quantifier> X<*> X<+> X<?> X<{n}> X<{n,}> X<{n,m}>
12602105
12612106=end original
12622107
2108Quantifiers are used when a particular portion of a pattern needs to
2109match a certain number (or numbers) of times. If there isn't a
2110quantifier the number of times to match is exactly one.
12632111以下の標準的な量指定子を使えます:
12642112X<metacharacter> X<quantifier> X<*> X<+> X<?> X<{n}> X<{n,}> X<{n,m}>
12652113
12662114=begin original
12672115
12682116 * Match 0 or more times
12692117 + Match 1 or more times
12702118 ? Match 1 or 0 times
12712119 {n} Match exactly n times
12722120 {n,} Match at least n times
12732121 {n,m} Match at least n but not more than m times
12742122
12752123=end original
12762124
12772125 * 0 回以上マッチング
12782126 + 1 回以上マッチング
12792127 ? 0 回または 1 回マッチング
12802128 {n} 正確に n 回マッチング
12812129 {n,} 最低 n 回マッチング
12822130 {n,m} n 回以上 m 回以下マッチング
12832131
12842132=begin original
12852133
1286(If a curly bracket occurs in any other context and does not form part of
2134(If a non-escaped curly bracket occurs in a context other than one of
1287a backslashed sequence like C<\x{...}>, it is treated
2135the quantifiers listed above, where it does not form part of a
1288as a regular character. In particular, the lower quantifier bound
2136backslashed sequence like C<\x{...}>, it is either a fatal syntax error,
1289is not optional. However, in Perl v5.18, it is planned to issue a
2137or treated as a regular character, generally with a deprecation warning
1290deprecation warning for all such occurrences, and in Perl v5.20 to
2138raised. To escape it, you can precede it with a backslash (C<"\{">) or
1291require literal uses of a curly bracket to be escaped, say by preceding
2139enclose it within square brackets (C<"[{]">).
1292them with a backslash or enclosing them within square brackets, (C<"\{">
2140This change will allow for future syntax extensions (like making the
1293or C<"[{]">). This change will allow for future syntax extensions (like
2141lower bound of a quantifier optional), and better error checking of
1294making the lower bound of a quantifier optional), and better error
2142quantifiers).
1295checking of quantifiers. Now, a typo in a quantifier silently causes
1296it to be treated as the literal characters. For example,
12972143
1298
12992144=end original
13002145
1301(これ以外のコンテキストで中かっこが使われて、C<\x{...}> のような
2146(前述した量指定子の一つ以外のコンテキストでエスケープされない中かっこが
1302バックスラッシュ付き並びの一部ではないときには、普通の文字として
2147使われて、C<\x{...}> のような逆スラッシュ付き並びの一部ではないときには、
1303使われます。
2148普通の文字として扱われるか、致命的エラーになり、どちらでも
1304また、下限の量指定子省略可能ではありせん
2149一般的に廃止予定警告が発生し
1305しかし、Perl v5.18 では、のようなもの全て廃し予定警告が発生し
2150れをエスケープするには、逆スラッシュを前置したり (C<"\{">)
1306Perl v.5.20 では、中かっこをリテラル使うには、逆スラッシュを前置した
2151かっこで囲んだ (C<"[{]">) できます。
1307大かっこで囲む (C<"\{"> または C<"[{]">) ことでエスケープすることが
1308要求されるようになる予定です。
13092152この変更により、(量指定子の加減をオプションにするような) 将来の
1310文法の拡張ができるようになり、量指定子に関するより良いエラーチェックが
2153文法の拡張ができるようになり、量指定子より良いエラーチェックが
13112154できるようになります。
1312現在のところ、量指定子のタイプミスは警告なしにリテラルな文字の並びとして
1313扱われます。
1314例えば:
13152155
1316 /o{4,3}/
1317
13182156=begin original
13192157
1320looks like a quantifier that matches 0 times, since 4 is greater than 3,
2158The C<"*"> quantifier is equivalent to C<{0,}>, the C<"+">
1321but it really means to match the sequence of six characters
2159quantifier to C<{1,}>, and the C<"?"> quantifier to C<{0,1}>. I<n> and I<m> are limited
1322S<C<"o { 4 , 3 }">>.)
1323
1324=end original
1325
1326これは、4 は 3 より大きいので、0 回マッチングする量指定子に見えますが、
1327これは実際には 6 文字並び
1328S<C<"o { 4 , 3 }">> にマッチングするという意味になります。)
1329
1330=begin original
1331
1332The "*" quantifier is equivalent to C<{0,}>, the "+"
1333quantifier to C<{1,}>, and the "?" quantifier to C<{0,1}>. n and m are limited
13342160to non-negative integral values less than a preset limit defined when perl is built.
13352161This is usually 32766 on the most common platforms. The actual limit can
13362162be seen in the error message generated by code such as this:
13372163
13382164=end original
13392165
1340"*" 量指定子は C<{0,}> と、"+" 量指定子は C<{1,}> と、
2166C<"*"> 量指定子は C<{0,}> と、C<"+"> 量指定子は C<{1,}> と、
1341"?" 量指定子は C<{0,1}> と等価です。
2167C<"?"> 量指定子は C<{0,1}> と等価です。
1342n 及び m は perl をビルドしたときに定義した既定の制限より小さな非負整数回に
2168I<n> I<m> は perl をビルドしたときに定義した既定の制限より小さな
1343制限されます。
2169非負整数回に制限されます。
13442170これは大抵のプラットフォームでは 32766 回になっています。
13452171実際の制限は次のようなコードを実行すると生成されるエラーメッセージで
13462172見ることができます:
13472173
13482174 $_ **= $_ , / {$_} / for 2 .. 42;
13492175
13502176=begin original
13512177
13522178By default, a quantified subpattern is "greedy", that is, it will match as
13532179many times as possible (given a particular starting location) while still
13542180allowing the rest of the pattern to match. If you want it to match the
1355minimum number of times possible, follow the quantifier with a "?". Note
2181minimum number of times possible, follow the quantifier with a C<"?">. Note
13562182that the meanings don't change, just the "greediness":
13572183X<metacharacter> X<greedy> X<greediness>
13582184X<?> X<*?> X<+?> X<??> X<{n}?> X<{n,}?> X<{n,m}?>
13592185
13602186=end original
13612187
13622188デフォルトでは、パターンで行われる量指定は「貪欲」です;
13632189つまりそれはパターンの残りの部分が可能な範囲で、
13642190(始めた地点から)可能な限り多くを先にあるパターンでマッチングさせます。
13652191もし最小回数でのマッチングを行いたいのであれば、量指定子の後ろに
1366"?" を続けます。
2192C<"?"> を続けます。
13672193意味は変更されずに「貪欲さ」だけを変更できます:
13682194X<metacharacter> X<greedy> X<greediness>
13692195X<?> X<*?> X<+?> X<??> X<{n}?> X<{n,}?> X<{n,m}?>
13702196
13712197=begin original
13722198
13732199 *? Match 0 or more times, not greedily
13742200 +? Match 1 or more times, not greedily
13752201 ?? Match 0 or 1 time, not greedily
13762202 {n}? Match exactly n times, not greedily (redundant)
13772203 {n,}? Match at least n times, not greedily
13782204 {n,m}? Match at least n but not more than m times, not greedily
13792205
13802206=end original
13812207
13822208 *? 0 回以上の貪欲でないマッチング
13832209 +? 1 回以上の貪欲でないマッチング
13842210 ?? 0 回または 1 回の貪欲でないマッチング
13852211 {n}? ちょうど n 回の貪欲でないマッチング (冗長)
13862212 {n,}? n 回以上の貪欲でないマッチング
13872213 {n,m}? n 回以上 m 回以下の貪欲でないマッチング
13882214
13892215=begin original
13902216
1391By default, when a quantified subpattern does not allow the rest of the
2217Normally when a quantified subpattern does not allow the rest of the
13922218overall pattern to match, Perl will backtrack. However, this behaviour is
13932219sometimes undesirable. Thus Perl provides the "possessive" quantifier form
13942220as well.
13952221
13962222=end original
13972223
1398デフォルトでは、パターンのうちの量指定された一部によってパターン全体が
2224通常、パターンのうちの量指定された一部によってパターン全体が
13992225マッチングに失敗したとき、Perl はバックトラックを行います。
14002226しかしこの振る舞いは望まれないこともあります。
14012227そのため、Perl は「絶対最大量(possessive)」量指定形式も提供しています。
14022228
14032229=begin original
14042230
14052231 *+ Match 0 or more times and give nothing back
14062232 ++ Match 1 or more times and give nothing back
14072233 ?+ Match 0 or 1 time and give nothing back
14082234 {n}+ Match exactly n times and give nothing back (redundant)
14092235 {n,}+ Match at least n times and give nothing back
14102236 {n,m}+ Match at least n but not more than m times and give nothing back
14112237
14122238=end original
14132239
14142240 *+ 0 回以上マッチングして何も返さない
14152241 ++ 1 回以上マッチングして何も返さない
14162242 ?+ 0 回または 1 回マッチングして何も返さない
14172243 {n}+ ちょうど n 回のマッチングして何も返さない (冗長)
14182244 {n,}+ n 回以上のマッチングして何も返さない
14192245 {n,m}+ n 回以上 m 回以下マッチングして何も返さない
14202246
14212247=begin original
14222248
14232249For instance,
14242250
14252251=end original
14262252
14272253例えば、
14282254
14292255 'aaaa' =~ /a++a/
14302256
14312257=begin original
14322258
1433will never match, as the C<a++> will gobble up all the C<a>'s in the
2259will never match, as the C<a++> will gobble up all the C<"a">'s in the
14342260string and won't leave any for the remaining part of the pattern. This
14352261feature can be extremely useful to give perl hints about where it
14362262shouldn't backtrack. For instance, the typical "match a double-quoted
14372263string" problem can be most efficiently performed when written as:
14382264
14392265=end original
14402266
1441は、C<a++> が文字列中の全ての C<a> を飲み込んでしまい、
2267は、C<a++> が文字列中の全ての C<"a"> を飲み込んでしまい、
14422268後に何も残さないためマッチングしません。
14432269この機能はバックトラックするべきでない場所のヒントを perl に
14442270与えるのに非常に便利です。
14452271例えば、典型的な「ダブルクォート文字列のマッチング」問題で次のように
14462272書くととても効率的になります:
14472273
14482274 /"(?:[^"\\]++|\\.)*+"/
14492275
14502276=begin original
14512277
14522278as we know that if the final quote does not match, backtracking will not
14532279help. See the independent subexpression
14542280L</C<< (?>pattern) >>> for more details;
14552281possessive quantifiers are just syntactic sugar for that construct. For
14562282instance the above example could also be written as follows:
14572283
14582284=end original
14592285
14602286見ての通り最後のクォートがマッチングしなかったとき、バックトラックは
14612287役に立ちません。
14622288詳細は独立したサブパターン L</C<< (?>pattern) >>> を参照してください;
14632289絶対最大量指定子はまさにその構文糖です。
14642290例えばこの例は次のようにも書けます:
14652291
14662292 /"(?>(?:(?>[^"\\]+)|\\.)*)"/
14672293
2294=begin original
2295
2296Note that the possessive quantifier modifier can not be be combined
2297with the non-greedy modifier. This is because it would make no sense.
2298Consider the follow equivalency table:
2299
2300=end original
2301
2302絶対最大量指定修飾子は非貪欲修飾子と結合できないことに注意してください。
2303これは無意味だからです。
2304次の等価性表を考慮してください:
2305
2306 Illegal Legal
2307 ------------ ------
2308 X??+ X{0}
2309 X+?+ X{1}
2310 X{min,max}?+ X{min}
2311
14682312=head3 Escape sequences
14692313
14702314(エスケープシーケンス)
14712315
14722316=begin original
14732317
14742318Because patterns are processed as double-quoted strings, the following
14752319also work:
14762320
14772321=end original
14782322
14792323パターンはダブルクォート文字列として処理されるため、
14802324以下のエスケープ文字も動作します:
14812325X<\t> X<\n> X<\r> X<\f> X<\e> X<\a> X<\l> X<\u> X<\L> X<\U> X<\E> X<\Q>
14822326X<\0> X<\c> X<\N{}> X<\x>
14832327
14842328=begin original
14852329
14862330 \t tab (HT, TAB)
14872331 \n newline (LF, NL)
14882332 \r return (CR)
14892333 \f form feed (FF)
14902334 \a alarm (bell) (BEL)
14912335 \e escape (think troff) (ESC)
14922336 \cK control char (example: VT)
14932337 \x{}, \x00 character whose ordinal is the given hexadecimal number
14942338 \N{name} named Unicode character or character sequence
14952339 \N{U+263D} Unicode character (example: FIRST QUARTER MOON)
14962340 \o{}, \000 character whose ordinal is the given octal number
14972341 \l lowercase next char (think vi)
14982342 \u uppercase next char (think vi)
1499 \L lowercase till \E (think vi)
2343 \L lowercase until \E (think vi)
1500 \U uppercase till \E (think vi)
2344 \U uppercase until \E (think vi)
1501 \Q quote (disable) pattern metacharacters till \E
2345 \Q quote (disable) pattern metacharacters until \E
15022346 \E end either case modification or quoted section, think vi
15032347
15042348=end original
15052349
15062350 \t タブ (水平タブ;HT、TAB)
15072351 \n 改行 (LF、NL)
15082352 \r 復帰 (CR)
15092353 \f フォームフィード (FF)
15102354 \a アラーム (ベル) (BEL)
15112355 \e エスケープ (troff 的) (ESC)
15122356 \cK 制御文字 (例: VT)
15132357 \x{}, \x00 16 進数で番号指定された文字
15142358 \N{name} 名前付きユニコード文字または文字並び
15152359 \N{U+263D} Unicode 文字 (例: FIRST QUARTER MOON)
15162360 \o{}, \000 8 進数で番号指定された文字
15172361 \l 次の文字を小文字に (vi 的)
15182362 \u 次の文字を大文字に (vi 的)
15192363 \L \E まで小文字に (vi 的)
15202364 \U \E まで大文字に (vi 的)
15212365 \Q \E までパターンメタ文字の無効化(Quote)
15222366 \E 大文字小文字変更またはクォートの終端 (vi 的)
15232367
15242368=begin original
15252369
15262370Details are in L<perlop/Quote and Quote-like Operators>.
15272371
15282372=end original
15292373
15302374詳細は L<perlop/Quote and Quote-like Operators> にあります。
15312375
15322376=head3 Character Classes and other Special Escapes
15332377
15342378(文字クラス及び他の特殊なエスケープ)
15352379
15362380=begin original
15372381
15382382In addition, Perl defines the following:
15392383X<\g> X<\k> X<\K> X<backreference>
15402384
15412385=end original
15422386
15432387さらに、Perl は以下のものを定義します:
15442388X<\g> X<\k> X<\K> X<backreference>
15452389
15462390=begin original
15472391
15482392 Sequence Note Description
15492393 [...] [1] Match a character according to the rules of the
15502394 bracketed character class defined by the "...".
15512395 Example: [a-z] matches "a" or "b" or "c" ... or "z"
15522396 [[:...:]] [2] Match a character according to the rules of the POSIX
15532397 character class "..." within the outer bracketed
15542398 character class. Example: [[:upper:]] matches any
15552399 uppercase character.
2400 (?[...]) [8] Extended bracketed character class
15562401 \w [3] Match a "word" character (alphanumeric plus "_", plus
15572402 other connector punctuation chars plus Unicode
15582403 marks)
15592404 \W [3] Match a non-"word" character
15602405 \s [3] Match a whitespace character
15612406 \S [3] Match a non-whitespace character
15622407 \d [3] Match a decimal digit character
15632408 \D [3] Match a non-digit character
15642409 \pP [3] Match P, named property. Use \p{Prop} for longer names
15652410 \PP [3] Match non-P
15662411 \X [4] Match Unicode "eXtended grapheme cluster"
1567 \C Match a single C-language char (octet) even if that is
1568 part of a larger UTF-8 character. Thus it breaks up
1569 characters into their UTF-8 bytes, so you may end up
1570 with malformed pieces of UTF-8. Unsupported in
1571 lookbehind.
15722412 \1 [5] Backreference to a specific capture group or buffer.
15732413 '1' may actually be any positive integer.
15742414 \g1 [5] Backreference to a specific or previous group,
15752415 \g{-1} [5] The number may be negative indicating a relative
15762416 previous group and may optionally be wrapped in
15772417 curly brackets for safer parsing.
15782418 \g{name} [5] Named backreference
15792419 \k<name> [5] Named backreference
15802420 \K [6] Keep the stuff left of the \K, don't include it in $&
1581 \N [7] Any character but \n (experimental). Not affected by
2421 \N [7] Any character but \n. Not affected by /s modifier
1582 /s modifier
15832422 \v [3] Vertical whitespace
15842423 \V [3] Not vertical whitespace
15852424 \h [3] Horizontal whitespace
15862425 \H [3] Not horizontal whitespace
15872426 \R [4] Linebreak
15882427
15892428=end original
15902429
15912430 Sequence Note Description
15922431 [...] [1] "..." で定義された大かっこ文字クラスのルールに従う文字に
15932432 マッチング。
15942433 例: [a-z] は "a", "b", "c", ... "z" にマッチング。
15952434 [[:...:]] [2] 外側の大かっこ文字クラスの内側の POSIX 文字クラスに
15962435 従う文字にマッチング。
15972436 例: [[:upper:]] は任意の大文字にマッチング。
2437 (?[...]) [8] 拡張大かっこ文字クラス
15982438 \w [3] "単語" 文字にマッチング (英数字及び "_" に加えて、
15992439 その他の接続句読点文字と Unicode マークにマッチング)
16002440 \W [3] 非"単語"文字にマッチング
16012441 \s [3] 空白文字にマッチング
16022442 \S [3] 非空白文字にマッチング
16032443 \d [3] 10 進数字にマッチング
16042444 \D [3] 非数字にマッチング
16052445 \pP [3] 名前属性 P にマッチング. 長い名前であれば \p{Prop}
16062446 \PP [3] P以外にマッチング
16072447 \X [4] Unicode 拡張書記素クラスタ("eXtended grapheme cluster")にマッチング
1608 \C より大きな UTF-8 文字の一部であっても、1つの C 言語の文字 (オクテット)にマッチング
1609 従って文字をUTF-8バイト列へと変換するので、壊れた
1610 UTF-8 片となるかもしれません; 後読みは対応していません
16112448 \1 [5] 指定した捕捉グループやバッファへの後方参照。
16122449 '1' には正の整数を指定できます。
16132450 \g1 [5] 指定したまたは前のグループへの後方参照
16142451 \g{-1} [5] 数値は相対的に前のグループを示す負の値にもできます、また
16152452 任意で安全にパースするために波かっこで括ることもできます
16162453 \g{name} [5] 名前指定の後方参照
16172454 \k<name> [5] 名前指定の後方参照
16182455 \K [6] \K の左にある物を保持、$& に含めない
1619 \N [7] \n 以外の任意の文字 (実験的) /s 修飾子の影響は受けない
2456 \N [7] \n 以外の任意の文字; /s 修飾子の影響は受けない
16202457 \v [3] 垂直空白
16212458 \V [3] 垂直空白以外
16222459 \h [3] 水平空白
16232460 \H [3] 水平空白以外
16242461 \R [4] 行区切り
16252462
16262463=over 4
16272464
16282465=item [1]
16292466
16302467=begin original
16312468
16322469See L<perlrecharclass/Bracketed Character Classes> for details.
16332470
16342471=end original
16352472
16362473詳しくは L<perlrecharclass/Bracketed Character Classes> を参照してください。
16372474
16382475=item [2]
16392476
16402477=begin original
16412478
16422479See L<perlrecharclass/POSIX Character Classes> for details.
16432480
16442481=end original
16452482
16462483詳しくは L<perlrecharclass/POSIX Character Classes> を参照してください。
16472484
16482485=item [3]
16492486
16502487=begin original
16512488
16522489See L<perlrecharclass/Backslash sequences> for details.
16532490
16542491=end original
16552492
16562493詳しくは L<perlrecharclass/Backslash sequences> を参照してください。
16572494
16582495=item [4]
16592496
16602497=begin original
16612498
16622499See L<perlrebackslash/Misc> for details.
16632500
16642501=end original
16652502
16662503詳しくは L<perlrebackslash/Misc> を参照してください。
16672504
16682505=item [5]
16692506
16702507=begin original
16712508
16722509See L</Capture groups> below for details.
16732510
16742511=end original
16752512
16762513詳しくは以下の L</Capture groups> を参照してください。
16772514
16782515=item [6]
16792516
16802517=begin original
16812518
16822519See L</Extended Patterns> below for details.
16832520
16842521=end original
16852522
16862523詳しくは以下のSee L</Extended Patterns> を参照してください。
16872524
16882525=item [7]
16892526
16902527=begin original
16912528
16922529Note that C<\N> has two meanings. When of the form C<\N{NAME}>, it matches the
16932530character or character sequence whose name is C<NAME>; and similarly
16942531when of the form C<\N{U+I<hex>}>, it matches the character whose Unicode
16952532code point is I<hex>. Otherwise it matches any character but C<\n>.
16962533
16972534=end original
16982535
16992536C<\N> には二つの意味があることに注意してください。
17002537C<\N{NAME}> の形式では、これは名前が C<NAME> の文字または文字の並びに
17012538マッチングします;
17022539同様に、C<\N{U+I<wide hex char>}> の形式では、Unicode 符号位置が
17032540I<hex> の文字にマッチングします。
17042541そうでなければ、C<\n> 以外の任意の文字にマッチングします。
17052542
2543=item [8]
2544
2545=begin original
2546
2547See L<perlrecharclass/Extended Bracketed Character Classes> for details.
2548
2549=end original
2550
2551詳しくは L<perlrecharclass/Extended Bracketed Character Classes> を
2552参照してください。
2553
17062554=back
17072555
17082556=head3 Assertions
17092557
17102558(言明)
17112559
17122560=begin original
17132561
1714Perl defines the following zero-width assertions:
2562Besides L<C<"^"> and C<"$">|/Metacharacters>, Perl defines the following
2563zero-width assertions:
17152564X<zero-width assertion> X<assertion> X<regex, zero-width assertion>
17162565X<regexp, zero-width assertion>
17172566X<regular expression, zero-width assertion>
17182567X<\b> X<\B> X<\A> X<\Z> X<\z> X<\G>
17192568
17202569=end original
17212570
2571L<C<"^"> と C<"$">|/Metacharacters> の他に、
17222572Perl は以下のゼロ幅のアサーションを定義しています:
17232573X<zero-width assertion> X<assertion> X<regex, zero-width assertion>
17242574X<regexp, zero-width assertion>
17252575X<regular expression, zero-width assertion>
17262576X<\b> X<\B> X<\A> X<\Z> X<\z> X<\G>
17272577
1728 \b Match a word boundary
2578 \b{} Match at Unicode boundary of specified type
1729 \B Match except at a word boundary
2579 \B{} Match where corresponding \b{} doesn't match
1730 \A Match only at beginning of string
2580 \b Match a \w\W or \W\w boundary
1731 \Z Match only at end of string, or before newline at the end
2581 \B Match except at a \w\W or \W\w boundary
1732 \z Match only at end of string
2582 \A Match only at beginning of string
1733 \G Match only at pos() (e.g. at the end-of-match position
2583 \Z Match only at end of string, or before newline at the end
2584 \z Match only at end of string
2585 \G Match only at pos() (e.g. at the end-of-match position
17342586 of prior m//g)
17352587
17362588=begin original
17372589
2590A Unicode boundary (C<\b{}>), available starting in v5.22, is a spot
2591between two characters, or before the first character in the string, or
2592after the final character in the string where certain criteria defined
2593by Unicode are met. See L<perlrebackslash/\b{}, \b, \B{}, \B> for
2594details.
2595
2596=end original
2597
2598v5.22 から利用可能である Unicode 境界 (C<\b{}>) は、
2599Unicode で定義されたある種の基準に一致した、
2600二つの文字の間か、文字列の最初の文字の前か、
2601文字列の最後の文字の後の地点です。
2602詳しくは L<perlrebackslash/\b{}, \b, \B{}, \B> を参照してください。
2603
2604=begin original
2605
17382606A word boundary (C<\b>) is a spot between two characters
17392607that has a C<\w> on one side of it and a C<\W> on the other side
17402608of it (in either order), counting the imaginary characters off the
17412609beginning and end of the string as matching a C<\W>. (Within
17422610character classes C<\b> represents backspace rather than a word
17432611boundary, just as it normally does in any double-quoted string.)
1744The C<\A> and C<\Z> are just like "^" and "$", except that they
2612The C<\A> and C<\Z> are just like C<"^"> and C<"$">, except that they
17452613won't match multiple times when the C</m> modifier is used, while
1746"^" and "$" will match at every internal line boundary. To match
2614C<"^"> and C<"$"> will match at every internal line boundary. To match
17472615the actual end of the string and not ignore an optional trailing
17482616newline, use C<\z>.
17492617X<\b> X<\A> X<\Z> X<\z> X</m>
17502618
17512619=end original
17522620
17532621単語境界(C<\b>)はC<\W> にマッチングする文字列の始まりと終わりを
17542622連想するような、片側を C<\w>、もう片側を C<\W> で挟まれている点です。
17552623(文字クラスにおいては C<\b> は単語境界ではなくバックスペースを表します,
17562624ちょうどダブルクォート文字列と同じように。)
1757C<\A> 及び C<\Z> は "^" 及び "$" と同様ですが、C</m> 修飾子が
2625C<\A> 及び C<\Z> は C<"^"> 及び C<"$"> と同様ですが、C</m> 修飾子が
1758指定されているときに "^" 及び "$" は全ての内部的な行境界に
2626指定されているときに C<"^"> 及び C<"$"> は全ての内部的な行境界に
17592627マッチングするのに対して C<\A> 及び C<\Z> は複数回のマッチングには
17602628なりません。
17612629文字列の本当の末尾にマッチングさせ、省略可能である末尾の改行を
17622630無視しないようにする C<\z> を使います。
17632631X<\b> X<\A> X<\Z> X<\z> X</m>
17642632
17652633=begin original
17662634
17672635The C<\G> assertion can be used to chain global matches (using
17682636C<m//g>), as described in L<perlop/"Regexp Quote-Like Operators">.
17692637It is also useful when writing C<lex>-like scanners, when you have
17702638several patterns that you want to match against consequent substrings
17712639of your string; see the previous reference. The actual location
17722640where C<\G> will match can also be influenced by using C<pos()> as
17732641an lvalue: see L<perlfunc/pos>. Note that the rule for zero-length
17742642matches (see L</"Repeated Patterns Matching a Zero-length Substring">)
17752643is modified somewhat, in that contents to the left of C<\G> are
17762644not counted when determining the length of the match. Thus the following
17772645will not match forever:
17782646X<\G>
17792647
17802648=end original
17812649
17822650C<\G> アサーションはグローバルなマッチング(C<m//g>)を連結するために
17832651使います; これは L<perlop/"Regexp Quote-Like Operators"> にも説明されています。
17842652これは文字列に対していくつかのパターンを次々にマッチングさせたいといった、
17852653C<lex> 風のスキャナを書きたいときにも便利です; 以前のリファレンスを
17862654参照してください。
17872655C<\G> が実際にマッチングできる位置は C<pos()> を左辺値として
17882656使うことで変更できます: L<perlfunc/pos> を参照してください。
17892657ゼロ幅マッチング
17902658(L</"Repeated Patterns Matching a Zero-length Substring"> を参照してください)
17912659のルールは少し変化することに注意してください、
17922660C<\G> の左にある内容はマッチングの長さを決定するときに
17932661数えられません。
17942662従って次のコードは永遠にマッチングしません:
17952663X<\G>
17962664
17972665 my $string = 'ABC';
17982666 pos($string) = 1;
17992667 while ($string =~ /(.\G)/g) {
18002668 print $1;
18012669 }
18022670
18032671=begin original
18042672
18052673It will print 'A' and then terminate, as it considers the match to
18062674be zero-width, and thus will not match at the same position twice in a
18072675row.
18082676
18092677=end original
18102678
18112679これはゼロ幅へのマッチングと見なされ、'A' を出力し終了するので、
18122680行の中で同じ場所に二度はマッチングしません。
18132681
18142682=begin original
18152683
18162684It is worth noting that C<\G> improperly used can result in an infinite
18172685loop. Take care when using patterns that include C<\G> in an alternation.
18182686
18192687=end original
18202688
18212689適切に使われていない C<\G> は無限ループとなり何の価値もありません。
18222690代替(alternation; C<|>)の中に C<\G> を含んでいるパターンを使う際には
18232691十分注意してください。
18242692
2693=begin original
2694
2695Note also that C<s///> will refuse to overwrite part of a substitution
2696that has already been replaced; so for example this will stop after the
2697first iteration, rather than iterating its way backwards through the
2698string:
2699
2700=end original
2701
2702C<s///> は置換部の既に置き換えられた部分を上書きすることを拒否することにも
2703注意してください; 従って例えばこれは文字列の後ろ向きの反復中ではなく、
2704最初の反復の後に停止します:
2705
2706 $_ = "123456789";
2707 pos = 6;
2708 s/.(?=.\G)/X/g;
2709 print; # prints 1234X6789, not XXXXX6789
2710
18252711=head3 Capture groups
18262712
18272713(捕捉グループ)
18282714
18292715=begin original
18302716
1831The bracketing construct C<( ... )> creates capture groups (also referred to as
2717The grouping construct C<( ... )> creates capture groups (also referred to as
18322718capture buffers). To refer to the current contents of a group later on, within
18332719the same pattern, use C<\g1> (or C<\g{1}>) for the first, C<\g2> (or C<\g{2}>)
18342720for the second, and so on.
18352721This is called a I<backreference>.
18362722X<regex, capture buffer> X<regexp, capture buffer>
18372723X<regex, capture group> X<regexp, capture group>
18382724X<regular expression, capture buffer> X<backreference>
18392725X<regular expression, capture group> X<backreference>
18402726X<\g{1}> X<\g{-1}> X<\g{name}> X<relative backreference> X<named backreference>
18412727X<named capture buffer> X<regular expression, named capture buffer>
18422728X<named capture group> X<regular expression, named capture group>
18432729X<%+> X<$+{name}> X<< \k<name> >>
18442730There is no limit to the number of captured substrings that you may use.
1845Groups are numbered with the leftmost open parenthesis being number 1, etc. If
2731Groups are numbered with the leftmost open parenthesis being number 1, I<etc>. If
18462732a group did not match, the associated backreference won't match either. (This
18472733can happen if the group is optional, or in a different branch of an
18482734alternation.)
1849You can omit the C<"g">, and write C<"\1">, etc, but there are some issues with
2735You can omit the C<"g">, and write C<"\1">, I<etc>, but there are some issues with
18502736this form, described below.
18512737
18522738=end original
18532739
1854かっこ構文 C<( ... )> は捕捉グループを作成します (そして捕捉バッファとして
2740グループ化構文 C<( ... )> は捕捉グループを作成します (そして捕捉バッファとして
18552741参照します)。
18562742同じパターンの中で、あるグループの現在の内容を後で参照するには、
18572743最初のものには C<\g1> (または C<\g{1}>) を、2 番目には C<\g2> (または
18582744C<\g{2}>) を、以下同様のものを使います。
18592745これを I<後方参照> (backreference) と呼びます。
18602746X<regex, capture buffer> X<regexp, capture buffer>
18612747X<regex, capture group> X<regexp, capture group>
18622748X<regular expression, capture buffer> X<backreference>
18632749X<regular expression, capture group> X<backreference>
18642750X<\g{1}> X<\g{-1}> X<\g{name}> X<relative backreference> X<named backreference>
18652751X<named capture buffer> X<regular expression, named capture buffer>
18662752X<named capture group> X<regular expression, named capture group>
18672753X<%+> X<$+{name}> X<< \k<name> >>
18682754使う捕捉部分文字列の数に制限はありません。
18692755グループはいちばん左の開きかっこを 1 番として番号付けされます。
18702756グループがマッチングしなかった場合、対応する後方参照もマッチングしません。
18712757(これはグループがオプションか、選択の異なる枝の場合に怒ることがあります。)
18722758C<"g"> を省略して C<"\1"> などと書くこともできますが、後で述べるように、
18732759この形式にはいくらかの問題があります。
18742760
18752761=begin original
18762762
18772763You can also refer to capture groups relatively, by using a negative number, so
18782764that C<\g-1> and C<\g{-1}> both refer to the immediately preceding capture
18792765group, and C<\g-2> and C<\g{-2}> both refer to the group before it. For
18802766example:
18812767
18822768=end original
18832769
18842770負数を使うことで捕捉グループを相対的に参照することもできます; C<\g-1> と
18852771C<\g{-1}> は両方とも直前の捕捉グループを参照し、C<\g-2> と C<\g{-2}> は
18862772両方ともその前のグループを参照します。
18872773例えば:
18882774
18892775 /
18902776 (Y) # group 1
18912777 ( # group 2
18922778 (X) # group 3
18932779 \g{-1} # backref to group 3
18942780 \g{-3} # backref to group 1
18952781 )
18962782 /x
18972783
18982784=begin original
18992785
19002786would match the same as C</(Y) ( (X) \g3 \g1 )/x>. This allows you to
19012787interpolate regexes into larger regexes and not have to worry about the
19022788capture groups being renumbered.
19032789
19042790=end original
19052791
19062792は C</(Y) ( (X) \g3 \g1 )/x> と同じマッチングとなります。
19072793これにより、正規表現をより大きな正規表現に挿入したときに、捕捉グループの
19082794番号を振り直す心配をする必要がなくなります。
19092795
19102796=begin original
19112797
19122798You can dispense with numbers altogether and create named capture groups.
19132799The notation is C<(?E<lt>I<name>E<gt>...)> to declare and C<\g{I<name>}> to
19142800reference. (To be compatible with .Net regular expressions, C<\g{I<name>}> may
19152801also be written as C<\k{I<name>}>, C<\kE<lt>I<name>E<gt>> or C<\k'I<name>'>.)
19162802I<name> must not begin with a number, nor contain hyphens.
19172803When different groups within the same pattern have the same name, any reference
19182804to that name assumes the leftmost defined group. Named groups count in
19192805absolute and relative numbering, and so can also be referred to by those
19202806numbers.
19212807(It's possible to do things with named capture groups that would otherwise
19222808require C<(??{})>.)
19232809
19242810=end original
19252811
19262812数値を全く使わずに、名前付き捕捉グループを作ることが出来ます。
19272813記法は、宣言が C<(?E<lt>I<name>E<gt>...)>、参照が C<\g{I<name>}> です。
19282814(.Net 正規表現との互換性のために、C<\g{I<name>}> は C<\k{I<name>}>,
19292815C<\kE<lt>I<name>E<gt>>, C<\k'I<name>'> とも書けます。)
19302816I<name> は数字で始まってはならず、ハイフンを含んではなりません。
19312817同じパターンの中に同じ名前の違うグループがある場合、
19322818この名前での参照は一番左で定義されたものを仮定します。
19332819名前付きグループも絶対や相対番号付けに含まれるので、
19342820番号で参照することも出来ます。
19352821(C<(??{})> が必要な場合でも名前付き捕捉グループを使うことが出来ます。)
19362822
19372823=begin original
19382824
19392825Capture group contents are dynamically scoped and available to you outside the
19402826pattern until the end of the enclosing block or until the next successful
19412827match, whichever comes first. (See L<perlsyn/"Compound Statements">.)
19422828You can refer to them by absolute number (using C<"$1"> instead of C<"\g1">,
1943etc); or by name via the C<%+> hash, using C<"$+{I<name>}">.
2829I<etc>); or by name via the C<%+> hash, using C<"$+{I<name>}">.
19442830
19452831=end original
19462832
19472833捕捉グループの内容は動的スコープを持ち、パターンの外側でも現在のブロックの
19482834末尾か次のマッチングの成功のどちらか早いほうまで利用可能です。
19492835(L<perlsyn/"Compound Statements"> を参照してください。)
19502836これらに対して (C<"\g1"> などの代わりに C<"$1"> を使って) 絶対値で
19512837参照するか、C<"$+{I<name>}"> を使って C<%+> 経由で名前で参照できます。
19522838
19532839=begin original
19542840
19552841Braces are required in referring to named capture groups, but are optional for
19562842absolute or relative numbered ones. Braces are safer when creating a regex by
19572843concatenating smaller strings. For example if you have C<qr/$a$b/>, and C<$a>
19582844contained C<"\g1">, and C<$b> contained C<"37">, you would get C</\g137/> which
19592845is probably not what you intended.
19602846
19612847=end original
19622848
19632849名前付き捕捉グループを参照するには中かっこが必要です;
19642850しかし、絶対数値や相対数値の場合はオプションです。
19652851より小さい文字列を結合して正規表現を作る場合は中かっこを使う方が安全です。
19662852例えば C<qr/$a$b/> で C<$a> に C<"\g1"> を含み、
19672853C<$b> に C<"37"> を含んでいるとき、
19682854結果は C</\g137/> となりますが、おそらく望んでいたものではないでしょう。
19692855
19702856=begin original
19712857
19722858The C<\g> and C<\k> notations were introduced in Perl 5.10.0. Prior to that
19732859there were no named nor relative numbered capture groups. Absolute numbered
19742860groups were referred to using C<\1>,
1975C<\2>, etc., and this notation is still
2861C<\2>, I<etc>., and this notation is still
19762862accepted (and likely always will be). But it leads to some ambiguities if
19772863there are more than 9 capture groups, as C<\10> could mean either the tenth
19782864capture group, or the character whose ordinal in octal is 010 (a backspace in
19792865ASCII). Perl resolves this ambiguity by interpreting C<\10> as a backreference
19802866only if at least 10 left parentheses have opened before it. Likewise C<\11> is
19812867a backreference only if at least 11 left parentheses have opened before it.
19822868And so on. C<\1> through C<\9> are always interpreted as backreferences.
19832869There are several examples below that illustrate these perils. You can avoid
19842870the ambiguity by always using C<\g{}> or C<\g> if you mean capturing groups;
19852871and for octal constants always using C<\o{}>, or for C<\077> and below, using 3
19862872digits padded with leading zeros, since a leading zero implies an octal
19872873constant.
19882874
19892875=end original
19902876
19912877C<\g> と C<\k> の記法は Perl 5.10.0 で導入されました。
19922878それより前には名前付きや相対数値指定の捕捉グループはありませんでした。
19932879絶対数値指定のグループは C<\1>, C<\2> などとして参照でき、この記法はまだ
19942880受け付けられます (そしておそらくいつも受け付けられます)。
19952881しかし、これは 9 を越える捕捉グループがあるとあいまいさがあります;
19962882C<\10> は 10 番目の捕捉グループとも、8 進数で 010 の文字(ASCII で
19972883バックスペース)とも解釈できます。
19982884Perl はこのあいまいさを以下のように解決します;
19992885C<\10> の場合、これの前に少なくとも 10 の左かっこがある場合にのみ
20002886これを後方参照として解釈します。
20012887同様に、C<\11> はその前に少なくとも 11 の左かっこがある場合にのみ
20022888これを後方参照として解釈します。
20032889以下同様です。
20042890C<\1> から C<\9> は常に後方参照として解釈されます。
20052891これを図示するいくつかの例が後にあります。
20062892捕捉グループを意味する場合は常に C<\g{}> や C<\g> を使うことで
20072893あいまいさを避けられます;
20082894そして 8 進定数については常に C<\o{}> を使うか、C<\077> 以下の場合は、
20092895先頭に 0 を付けて 3 桁にします; なぜなら先頭に 0 が付くと
201028968 進定数を仮定するからです。
20112897
20122898=begin original
20132899
20142900The C<\I<digit>> notation also works in certain circumstances outside
20152901the pattern. See L</Warning on \1 Instead of $1> below for details.
20162902
20172903=end original
20182904
20192905C<\I<digit>> 記法は、ある種の状況ではパターンの外側でも動作します。
20202906詳しくは後述する L</Warning on \1 Instead of $1> を参照して下さい。
20212907
20222908=begin original
20232909
20242910Examples:
20252911
20262912=end original
20272913
20282914例:
20292915
20302916 s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words
20312917
20322918 /(.)\g1/ # find first doubled char
20332919 and print "'$1' is the first doubled character\n";
20342920
20352921 /(?<char>.)\k<char>/ # ... a different way
20362922 and print "'$+{char}' is the first doubled character\n";
20372923
20382924 /(?'char'.)\g1/ # ... mix and match
20392925 and print "'$1' is the first doubled character\n";
20402926
20412927 if (/Time: (..):(..):(..)/) { # parse out values
20422928 $hours = $1;
20432929 $minutes = $2;
20442930 $seconds = $3;
20452931 }
20462932
20472933 /(.)(.)(.)(.)(.)(.)(.)(.)(.)\g10/ # \g10 is a backreference
20482934 /(.)(.)(.)(.)(.)(.)(.)(.)(.)\10/ # \10 is octal
20492935 /((.)(.)(.)(.)(.)(.)(.)(.)(.))\10/ # \10 is a backreference
20502936 /((.)(.)(.)(.)(.)(.)(.)(.)(.))\010/ # \010 is octal
20512937
20522938 $a = '(.)\1'; # Creates problems when concatenated.
20532939 $b = '(.)\g{1}'; # Avoids the problems.
20542940 "aa" =~ /${a}/; # True
20552941 "aa" =~ /${b}/; # True
20562942 "aa0" =~ /${a}0/; # False!
20572943 "aa0" =~ /${b}0/; # True
20582944 "aa\x08" =~ /${a}0/; # True!
20592945 "aa\x08" =~ /${b}0/; # False
20602946
20612947=begin original
20622948
20632949Several special variables also refer back to portions of the previous
20642950match. C<$+> returns whatever the last bracket match matched.
20652951C<$&> returns the entire matched string. (At one point C<$0> did
20662952also, but now it returns the name of the program.) C<$`> returns
20672953everything before the matched string. C<$'> returns everything
20682954after the matched string. And C<$^N> contains whatever was matched by
20692955the most-recently closed group (submatch). C<$^N> can be used in
20702956extended patterns (see below), for example to assign a submatch to a
20712957variable.
20722958X<$+> X<$^N> X<$&> X<$`> X<$'>
20732959
20742960=end original
20752961
20762962いくつかの特殊変数もまた以前のマッチングの一部を参照しています。
20772963C<$+> は最後のマッチングしたブラケットマッチングを返します。
20782964C<$&> はマッチングした文字列全体を返します。
20792965(一頃は C<$0> もそうでしたが、現在ではこれはプログラム名を返します。)
20802966C<$`> はマッチングした文字列の前の全てを返します。
20812967C<$'> はマッチングした文字列の後の全てを返します。
20822968そして C<$^N> には一番最後に閉じたグループ(サブマッチング)に
20832969マッチングしたものを含んでいます。
20842970C<$^N> は例えばサブマッチングを変数に格納するため等に拡張パターンの中でも
20852971利用できます(後述)。
20862972X<$+> X<$^N> X<$&> X<$`> X<$'>
20872973
20882974=begin original
20892975
20902976These special variables, like the C<%+> hash and the numbered match variables
2091(C<$1>, C<$2>, C<$3>, etc.) are dynamically scoped
2977(C<$1>, C<$2>, C<$3>, I<etc>.) are dynamically scoped
20922978until the end of the enclosing block or until the next successful
20932979match, whichever comes first. (See L<perlsyn/"Compound Statements">.)
20942980X<$+> X<$^N> X<$&> X<$`> X<$'>
20952981X<$1> X<$2> X<$3> X<$4> X<$5> X<$6> X<$7> X<$8> X<$9>
20962982
20972983=end original
20982984
20992985C<%+> ハッシュのような特殊変数と、数値によるマッチング変数
21002986(C<$1>, C<$2>, C<$3> など)はブロックの終端または次のマッチング
21012987成功までのどちらか先に満たした方の、動的なスコープを持ちます。
21022988(L<perlsyn/"Compound Statements"> を参照してください。)
21032989X<$+> X<$^N> X<$&> X<$`> X<$'>
21042990X<$1> X<$2> X<$3> X<$4> X<$5> X<$6> X<$7> X<$8> X<$9>
21052991
21062992=begin original
21072993
21082994B<NOTE>: Failed matches in Perl do not reset the match variables,
21092995which makes it easier to write code that tests for a series of more
21102996specific cases and remembers the best match.
21112997
21122998=end original
21132999
21143000B<補足>: Perl において失敗したマッチングはマッチング変数をリセットしません;
21153001これはより特殊化させる一連のテストを書くことや、
21163002最善のマッチングを書くことを容易にします。
21173003
21183004=begin original
21193005
2120B<WARNING>: Once Perl sees that you need one of C<$&>, C<$`>, or
3006B<WARNING>: If your code is to run on Perl 5.16 or earlier,
3007beware that once Perl sees that you need one of C<$&>, C<$`>, or
21213008C<$'> anywhere in the program, it has to provide them for every
2122pattern match. This may substantially slow your program. Perl
3009pattern match. This may substantially slow your program.
2123uses the same mechanism to produce C<$1>, C<$2>, etc, so you also pay a
2124price for each pattern that contains capturing parentheses. (To
3011=end original
2125avoid this cost while retaining the grouping behaviour, use the
3013B<警告>: あなたのコードが Perl 5.16 以前で実行されるものの場合、
3014Perl は、一旦プログラム中のどこかで C<$&>, C<$`>, C<$'> の
3015いずれかを必要としていることを見つけると、全てのパターンマッチングで
3016それらを提供しなければなあらないことに注意してください。
3017これはあなたのプログラムを大幅に遅くさせるでしょう。
3018
3019=begin original
3020
3021Perl uses the same mechanism to produce C<$1>, C<$2>, I<etc>, so you also
3022pay a price for each pattern that contains capturing parentheses.
3023(To avoid this cost while retaining the grouping behaviour, use the
21263024extended regular expression C<(?: ... )> instead.) But if you never
21273025use C<$&>, C<$`> or C<$'>, then patterns I<without> capturing
21283026parentheses will not be penalized. So avoid C<$&>, C<$'>, and C<$`>
21293027if you can, but if you can't (and some algorithms really appreciate
21303028them), once you've used them once, use them at will, because you've
2131already paid the price. As of 5.005, C<$&> is not so costly as the
3029already paid the price.
2132other two.
21333030X<$&> X<$`> X<$'>
21343031
21353032=end original
21363033
2137B<警告>: Perl は、一旦プログラム中のどこかで C<$&>, C<$`>, C<$'> の
2138いずれかを必要としていることを見つけると、全てのパターンマッチングで
2139それらを提供しなければなりません。
2140これはあなたのプログラムを大幅に遅くさせるでしょう。
21413034Perl は C<$1>, C<$2> 等の生成にも同じメカニズムを使っているので、
21423035キャプチャのかっこに含まれるそれぞれのパターンにも
21433036同じ料金を払っています。
21443037(グループ化の振る舞いを維持しつつこのコストを削減するには
21453038拡張正規表現 C<(?: ... )> を代わりに使います
21463039(訳注:Perl拡張というだけで C</x> 修飾子は不要)。)
21473040ですが C<$&>, C<$`> または C<$'> を一度も使わなければ、
21483041キャプチャのかっこをI<もたない>パターンではこの不利益はなくなります。
21493042この為、可能であれば C<$&>, C<$'>, 及び C<$`> を削除しましょう:
21503043しかしそれができなかった(そしてそれらを
21513044本当に理解しているアルゴリズムがあるのであれば)、一旦
21523045それらを使った時点でそれ以降は自由にそれらを使うことができます;
21533046なぜならあなたは(一度使った時点で)既に代価を払っているので。
21545.005 であれば C<$&> は他の2つほど高価ではありません。
21553047X<$&> X<$`> X<$'>
21563048
21573049=begin original
21583050
2159As a workaround for this problem, Perl 5.10.0 introduces C<${^PREMATCH}>,
3051Perl 5.16 introduced a slightly more efficient mechanism that notes
3052separately whether each of C<$`>, C<$&>, and C<$'> have been seen, and
3053thus may only need to copy part of the string. Perl 5.20 introduced a
3054much more efficient copy-on-write mechanism which eliminates any slowdown.
3055
3056=end original
3057
3058Perl 5.16 では、C<$`>, C<$&>, C<$'> のそれぞれが現れるかどうかを
3059個別に記録するという少し効率的な機構が導入され、
3060従って文字列の一部分だけコピーするようになりました。
3061Perl 5.20 では、全く遅くならない遙かに効率的なコピーオンライト機構を
3062導入しました。
3063
3064=begin original
3065
3066As another workaround for this problem, Perl 5.10.0 introduced C<${^PREMATCH}>,
21603067C<${^MATCH}> and C<${^POSTMATCH}>, which are equivalent to C<$`>, C<$&>
21613068and C<$'>, B<except> that they are only guaranteed to be defined after a
21623069successful match that was executed with the C</p> (preserve) modifier.
21633070The use of these variables incurs no global performance penalty, unlike
2164their punctuation char equivalents, however at the trade-off that you
3071their punctuation character equivalents, however at the trade-off that you
2165have to tell perl when you want to use them.
3072have to tell perl when you want to use them. As of Perl 5.20, these three
3073variables are equivalent to C<$`>, C<$&> and C<$'>, and C</p> is ignored.
21663074X</p> X<p modifier>
21673075
21683076=end original
21693077
2170この問題に対する解決策として、Perl 5.10.0 からは C<$`>, C<$&>, C<$'> と
3078この問題に対するもう一つの解決策として、Perl 5.10.0 からは
3079C<$`>, C<$&>, C<$'> と
21713080等価だけれども C</p> (preseve) 修飾子を伴って実行されたマッチングが
21723081成功した後でのみ定義されることが保証される C<${^PREMATCH}>、
21733082C<${^MATCH}> 及び C<${^POSTMATCH}> を導入しました。
21743083これらの変数の使用は利用したいときに perl に伝える必要がある代わりに、
21753084等価な記号変数とは違い全体的なパフォーマンスの低下を引き起こしません。
3085Perl 5.20 からこれら三つの変数は C<$`>, C<$&>, C<$'> と等価となり、
3086C</p> は無視されます。
21763087X</p> X<p modifier>
21773088
21783089=head2 Quoting metacharacters
21793090
21803091(メタ文字のクォート)
21813092
21823093=begin original
21833094
21843095Backslashed metacharacters in Perl are alphanumeric, such as C<\b>,
21853096C<\w>, C<\n>. Unlike some other regular expression languages, there
21863097are no backslashed symbols that aren't alphanumeric. So anything
2187that looks like \\, \(, \), \<, \>, \{, or \} is always
3098that looks like C<\\>, C<\(>, C<\)>, C<\[>, C<\]>, C<\{>, or C<\}> is
3099always
21883100interpreted as a literal character, not a metacharacter. This was
21893101once used in a common idiom to disable or quote the special meanings
21903102of regular expression metacharacters in a string that you want to
21913103use for a pattern. Simply quote all non-"word" characters:
21923104
21933105=end original
21943106
2195Perl においてバックスラッシュで表現されるメタ文字は C<\b>, C<\w>,
3107Perl においてスラッシュで表現されるメタ文字は C<\b>, C<\w>,
21963108C<\n> のように英数字です。
2197他の正規表現言語とは異なり、英数字でないシンボルのバックスラッシュは
3109他の正規表現言語とは異なり、英数字でないスラッシュ付きシンボル
21983110ありません。
2199なので \\, \(, \), \<, \>, \{, \} といったものは全てメタ文字ではなく
3111なので C<\\>, C<\(>, C<\)>, C<\[>, C<\]>, C<\{>, or C<\}> といったものは
2200リテラル文字です。
3112全てメタ文字ではなくリテラル文字です。
22013113これはパターンで使いたい文字列の中で正規表現のメタ文字としての特殊な意味を
22023114無効化またはクォートするための一般的な指標として使われてきました。
22033115「単語」でない全ての文字は単にクォートします:
22043116
22053117 $pattern =~ s/(\W)/\\$1/g;
22063118
22073119=begin original
22083120
22093121(If C<use locale> is set, then this depends on the current locale.)
2210Today it is more common to use the quotemeta() function or the C<\Q>
3122Today it is more common to use the C<L<quotemeta()|perlfunc/quotemeta>>
2211metaquoting escape sequence to disable all metacharacters' special
3123function or the C<\Q> metaquoting escape sequence to disable all
2212meanings like this:
3124metacharacters' special meanings like this:
22133125
22143126=end original
22153127
22163128(もし C<use locale> が有効であれば、これは現在のロケールに依存します。)
22173129今日では特殊な意味を持つメタ文字を全て無効にするためには次のように
2218quotemeta() 関数か C<\Q> メタクォートエスケープシーケンスを使うのが
3130C<L<quotemeta()|perlfunc/quotemeta>> 関数か C<\Q> メタクォート
2219より一般的です:
3131エスケープシーケンスを使うのがより一般的です:
22203132
22213133 /$unquoted\Q$quoted\E$unquoted/
22223134
22233135=begin original
22243136
22253137Beware that if you put literal backslashes (those not inside
22263138interpolated variables) between C<\Q> and C<\E>, double-quotish
22273139backslash interpolation may lead to confusing results. If you
22283140I<need> to use literal backslashes within C<\Q...\E>,
22293141consult L<perlop/"Gory details of parsing quoted constructs">.
22303142
22313143=end original
22323144
2233C<\Q> 及び C<\E> の間でリテラルとしてバックスラッシュをおくとき
3145C<\Q> 及び C<\E> の間でリテラルとしてスラッシュをおくとき
2234(埋め込んだ変数の中でではない)には、二重にクォートしたバックスラッシュの
3146(埋め込んだ変数の中でではない)には、二重にクォートしたスラッシュの
22353147埋め込みは困惑した結果となるでしょう。
2236もし C<\Q...\E> でリテラルとしてのバックスラッシュを使う
3148もし C<\Q...\E> でリテラルとしてのスラッシュを使う
22373149I<必要がある> のなら、
22383150L<perlop/"Gory details of parsing quoted constructs"> を参照してください。
22393151
22403152=begin original
22413153
22423154C<quotemeta()> and C<\Q> are fully described in L<perlfunc/quotemeta>.
22433155
22443156=end original
22453157
22463158C<quotemeta()> と C<\Q> は L<perlfunc/quotemeta> に完全に記述されています。
22473159
22483160=head2 Extended Patterns
22493161
22503162(拡張パターン)
22513163
22523164=begin original
22533165
22543166Perl also defines a consistent extension syntax for features not
22553167found in standard tools like B<awk> and
22563168B<lex>. The syntax for most of these is a
22573169pair of parentheses with a question mark as the first thing within
22583170the parentheses. The character after the question mark indicates
22593171the extension.
22603172
22613173=end original
22623174
22633175Perl は B<awk> や B<lex> といった標準的なツールでは見られない機能のための
22643176拡張構文も定義しています。
22653177これらのほとんどの構文は対のかっことかっこ内の最初に疑問符の形をとります。
22663178疑問符の後の文字で拡張を区別します。
22673179
22683180=begin original
22693181
2270The stability of these extensions varies widely. Some have been
2271part of the core language for many years. Others are experimental
2272and may change without warning or be completely removed. Check
2273the documentation on an individual feature to verify its current
2274status.
2275
2276=end original
2277
2278拡張構文の安定度は様々です。
2279中には長年言語コアの一部となっている物もあります。
2280そうでなく実験的に追加され警告なしに変更されたり削除されるものも
2281中にはあります。
2282それぞれのステータスに関しては個々の機能のドキュメントを確認してください。
2283
2284=begin original
2285
22863182A question mark was chosen for this and for the minimal-matching
22873183construct because 1) question marks are rare in older regular
22883184expressions, and 2) whenever you see one, you should stop and
22893185"question" exactly what is going on. That's psychology....
22903186
22913187=end original
22923188
22933189疑問符は 1) それが古い正規表現で使われることは稀であること、そして
229431902) それを見かけると何が行われるのか本当に「疑問に」思って止まることから、
22953191これのためと最小マッチング構成子のために選ばれました。
22963192これが心理学です…。
22973193
22983194=over 4
22993195
23003196=item C<(?#text)>
23013197X<(?#)>
23023198
23033199=begin original
23043200
2305A comment. The text is ignored. If the C</x> modifier enables
3201A comment. The text is ignored.
2306whitespace formatting, a simple C<#> will suffice. Note that Perl closes
3202Note that Perl closes
2307the comment as soon as it sees a C<)>, so there is no way to put a literal
3203the comment as soon as it sees a C<")">, so there is no way to put a literal
2308C<)> in the comment.
3204C<")"> in the comment. The pattern's closing delimiter must be escaped by
3205a backslash if it appears in the comment.
23093206
23103207=end original
23113208
23123209コメント。
23133210テキストは無視されます。
2314C</x> 修飾子よって空白の整形が有効されていれば単なる C<#> でも十分です。
3211Perl は C<")"> を見つけると直ぐコメントを閉じる点注意しくださ;
2315Perl C<)> を見つけると直ぐにコメントを閉じる点注意してださい;
3212この為リテラル C<")"> をコメントことはできません。
2316為リテラル C<)> をコメントおくことはできません。
3213パターン閉じ区切り文字がコメントに見えるようなものなら、
3214逆スラッシュでエスケープしなければなりません。
23173215
2318=item C<(?adlupimsx-imsx)>
3216=begin original
23193217
2320=item C<(?^alupimsx)>
3218See L</E<sol>x> for another way to have comments in patterns.
3219
3220=end original
3221
3222パターンの中にコメントを入れるもう一つの方法については
3223L</E<sol>x> を参照してください。
3224
3225=begin original
3226
3227Note that a comment can go just about anywhere, except in the middle of
3228an escape sequence. Examples:
3229
3230=end original
3231
3232コメントは、エスケープシーケンスの途中を除いて、
3233どこにでも入れることができることに注意してください。
3234例:
3235
3236 qr/foo(?#comment)bar/' # Matches 'foobar'
3237
3238 # The pattern below matches 'abcd', 'abccd', or 'abcccd'
3239 qr/abc(?#comment between literal and its quantifier){1,3}d/
3240
3241 # The pattern below generates a syntax error, because the '\p' must
3242 # be followed immediately by a '{'.
3243 qr/\p(?#comment between \p and its property name){Any}/
3244
3245 # The pattern below generates a syntax error, because the initial
3246 # '\(' is a literal opening parenthesis, and so there is nothing
3247 # for the closing ')' to match
3248 qr/\(?#the backslash means this isn't a comment)p{Any}/
3249
3250 # Comments can be used to fold long patterns into multiple lines
3251 qr/First part of a long regex(?#
3252 )remaining part/
3253
3254=item C<(?adlupimnsx-imnsx)>
3255
3256=item C<(?^alupimnsx)>
23213257X<(?)> X<(?^)>
23223258
23233259=begin original
23243260
23253261One or more embedded pattern-match modifiers, to be turned on (or
2326turned off, if preceded by C<->) for the remainder of the pattern or
3262turned off if preceded by C<"-">) for the remainder of the pattern or
23273263the remainder of the enclosing pattern group (if any).
23283264
23293265=end original
23303266
23313267一つもしくは複数のパターンマッチング修飾子;
23323268パターンの残りまたは(もしあれば)包含しているパターングループの残りで
2333有効にする(または C<-> が前置されていれば解除する)。
3269有効にする(または C<"-"> が前置されていれば解除する)。
23343270
23353271=begin original
23363272
2337This is particularly useful for dynamic patterns, such as those read in from a
3273This is particularly useful for dynamically-generated patterns,
3274such as those read in from a
23383275configuration file, taken from an argument, or specified in a table
23393276somewhere. Consider the case where some patterns want to be
23403277case-sensitive and some do not: The case-insensitive ones merely need to
23413278include C<(?i)> at the front of the pattern. For example:
23423279
23433280=end original
23443281
23453282これは設定ファイルから読む、引数から取る、どこかのテーブルで
2346指定されている箇所からダイナミックなパターンを使うときに特に便利です。
3283指定されている箇所から動的生成されたパターンを使うときに特に便利です。
23473284パターンの一部では大文字小文字を区別したいけれども別の箇所では
23483285区別しないといったケースを考えてみます: 区別をしない場所では
23493286単にパターンの先頭に C<(?i)> を含めるだけです。
23503287例えば:
23513288
23523289 $pattern = "foobar";
23533290 if ( /$pattern/i ) { }
23543291
23553292 # more flexible:
23563293
23573294 $pattern = "(?i)foobar";
23583295 if ( /$pattern/ ) { }
23593296
23603297=begin original
23613298
23623299These modifiers are restored at the end of the enclosing group. For example,
23633300
23643301=end original
23653302
23663303これらの修飾子は包含しているグループの最後で復元(restore)されます。
23673304例えば、
23683305
23693306 ( (?i) blah ) \s+ \g1
23703307
23713308=begin original
23723309
23733310will match C<blah> in any case, some spaces, and an exact (I<including the case>!)
23743311repetition of the previous word, assuming the C</x> modifier, and no C</i>
23753312modifier outside this group.
23763313
23773314=end original
23783315
23793316は C<blah> に大文字小文字の区別なくマッチングし、
23803317いくつかの空白、そして前の単語その物(I<大文字小文字の区別まで含めて>!)に
23813318再度マッチングします; ここではこのグループの外側で C</x> 修飾子を持ち、
23823319C</i> 修飾子を持たないものとします。
23833320
23843321=begin original
23853322
23863323These modifiers do not carry over into named subpatterns called in the
23873324enclosing group. In other words, a pattern such as C<((?i)(?&NAME))> does not
2388change the case-sensitivity of the "NAME" pattern.
3325change the case-sensitivity of the C<"NAME"> pattern.
23893326
23903327=end original
23913328
23923329これらの修飾子は囲まれたグループで呼び出された名前付き部分パターンには
23933330持ち越されません。
2394言い換えると、C<((?i)(?&NAME))> のようなパターンは、"NAME" パターンが
3331言い換えると、C<((?i)(?&NAME))> のようなパターンは、
2395大文字小文字を認識するのを変更しません。
3332C<"NAME"> パターンが大文字小文字を認識するのを変更しません。
23963333
23973334=begin original
23983335
3336A modifier is overridden by later occurrences of this construct in the
3337same scope containing the same modifier, so that
3338
3339=end original
3340
3341修飾子は、同じスコープ内で同じ修飾子を含む
3342この構文が後に出現すると上書きされるので:
3343
3344 /((?im)foo(?-m)bar)/
3345
3346=begin original
3347
3348matches all of C<foobar> case insensitively, but uses C</m> rules for
3349only the C<foo> portion. The C<"a"> flag overrides C<aa> as well;
3350likewise C<aa> overrides C<"a">. The same goes for C<"x"> and C<xx>.
3351Hence, in
3352
3353=end original
3354
3355は、C<foobar> のすべてに大文字小文字を区別せずにマッチングしますが、
3356C<foo> 部分のみに C</m> の規則を使います。
3357C<"a"> フラグは C<aa> も上書きします;
3358同様に、C<aa> も C<"a">を上書きします。
3359同じことが C<"x"> と C<xx> についても当てはまります。
3360したがって:
3361
3362 /(?-x)foo/xx
3363
3364=begin original
3365
3366both C</x> and C</xx> are turned off during matching C<foo>. And in
3367
3368=end original
3369
3370C</x> と C</xx> は両方とも、C<foo> のマッチング中はオフになります。
3371そして:
3372
3373 /(?x)foo/x
3374
3375=begin original
3376
3377C</x> but NOT C</xx> is turned on for matching C<foo>. (One might
3378mistakenly think that since the inner C<(?x)> is already in the scope of
3379C</x>, that the result would effectively be the sum of them, yielding
3380C</xx>. It doesn't work that way.) Similarly, doing something like
3381C<(?xx-x)foo> turns off all C<"x"> behavior for matching C<foo>, it is not
3382that you subtract 1 C<"x"> from 2 to get 1 C<"x"> remaining.
3383
3384=end original
3385
3386C<foo> にマッチングする間、C</xx> ではなく C</x> がオンになります。
3387(内部 C<(?x)> はすでに C</x> の範囲内にあるので、結果は実質的に
3388それらの和になり、C</xx> が生成されると誤って考えるかもしれません。
3389そうはなりません。)
3390同様に、C<(?xx-x)foo> のようなことをすると、C<foo> とマッチングする間
3391C<"x"> の動作がすべてオフになります;
3392二つの C<"x"> から一つ引いて一つの C<"x"> が残るということにはなりません。
3393
3394=begin original
3395
23993396Any of these modifiers can be set to apply globally to all regular
24003397expressions compiled within the scope of a C<use re>. See
24013398L<re/"'/flags' mode">.
24023399
24033400=end original
24043401
24053402それらの変更のどれもセットでき、C<use re>のスコープ内でグローバルに
24063403全てのコンパイルされた正規表現に適用されます。L<re/"'/flags' mode">
24073404を見てください。
24083405
24093406=begin original
24103407
24113408Starting in Perl 5.14, a C<"^"> (caret or circumflex accent) immediately
2412after the C<"?"> is a shorthand equivalent to C<d-imsx>. Flags (except
3409after the C<"?"> is a shorthand equivalent to C<d-imnsx>. Flags (except
24133410C<"d">) may follow the caret to override it.
24143411But a minus sign is not legal with it.
24153412
24163413=end original
24173414
24183415Perl 5.14から、C<"^">(キャレットか曲折アクセント)がC<"?">のすぐ
2419後ろにつくと、C<d-imsx>と同じになります。フラグ(C<"d">以外の)
3416後ろにつくと、C<d-imnsx> と同じになります。フラグ(C<"d">以外の)
24203417をキャレットに続けることで、上書きできます。
24213418ですが、マイナス記号は一緒に使えません。
24223419
24233420=begin original
24243421
2425Note that the C<a>, C<d>, C<l>, C<p>, and C<u> modifiers are special in
3422Note that the C<"a">, C<"d">, C<"l">, C<"p">, and C<"u"> modifiers are special in
2426that they can only be enabled, not disabled, and the C<a>, C<d>, C<l>, and
3423that they can only be enabled, not disabled, and the C<"a">, C<"d">, C<"l">, and
2427C<u> modifiers are mutually exclusive: specifying one de-specifies the
3424C<"u"> modifiers are mutually exclusive: specifying one de-specifies the
2428others, and a maximum of one (or two C<a>'s) may appear in the
3425others, and a maximum of one (or two C<"a">'s) may appear in the
24293426construct. Thus, for
24303427example, C<(?-p)> will warn when compiled under C<use warnings>;
24313428C<(?-d:...)> and C<(?dl:...)> are fatal errors.
24323429
24333430=end original
24343431
2435C<a>, C<d>, C<l>, C<p>, C<u> 修飾子は有効にできるのみで、無効にはできない点
3432C<"a">, C<"d">, C<"l">, C<"p">, C<"u"> 修飾子は有効にできるのみで、
2436そして C<a>, C<d>, C<l>, C<u> 修飾子は互いに排他であるという点で特別です:
3433無効にはできない点、 そして C<"a">, C<"d">, C<"l">, C<"u"> 修飾子は
3434互いに排他であるという点で特別です:
24373435一つを指定すると他のものの指定を解除し、構文中に最大で一つ (または二つの
2438C<a>) だけが現れます。
3436C<"a">) だけが現れます。
24393437従って 例えば C<(?-p)> は C<use warnings> の下でコンパイルされると
24403438警告を発します; C<(?-d:...)> と C<(?dl:...)> は致命的エラーです。
24413439
24423440=begin original
24433441
2444Note also that the C<p> modifier is special in that its presence
3442Note also that the C<"p"> modifier is special in that its presence
24453443anywhere in a pattern has a global effect.
24463444
24473445=end original
24483446
24493447パターン中のどこにあってもグローバルな影響があるという意味で
2450C<p> 修飾子が特別であることにも注意してください。
3448C<"p"> 修飾子が特別であることにも注意してください。
24513449
24523450=item C<(?:pattern)>
24533451X<(?:)>
24543452
2455=item C<(?adluimsx-imsx:pattern)>
3453=item C<(?adluimnsx-imnsx:pattern)>
24563454
2457=item C<(?^aluimsx:pattern)>
3455=item C<(?^aluimnsx:pattern)>
24583456X<(?^:)>
24593457
24603458=begin original
24613459
24623460This is for clustering, not capturing; it groups subexpressions like
2463"()", but doesn't make backreferences as "()" does. So
3461C<"()">, but doesn't make backreferences as C<"()"> does. So
24643462
24653463=end original
24663464
2467これはキャプチャではなくクラスタです; これは "()" のように部分式を
3465これはキャプチャではなくクラスタです; これは C<"()"> のように部分式を
2468グループ化しますが "()" が行うような後方参照は行いません。
3466グループ化しますが C<"()"> が行うような後方参照は行いません。
24693467つまり、
24703468
24713469 @fields = split(/\b(?:a|b|c)\b/)
24723470
24733471=begin original
24743472
2475is like
3473matches the same field delimiters as
24763474
24773475=end original
24783476
2479次と同様ですが
3477次と同じフィールド区切り文字にマッチングしますが:
24803478
24813479 @fields = split(/\b(a|b|c)\b/)
24823480
24833481=begin original
24843482
2485but doesn't spit out extra fields. It's also cheaper not to capture
3483but doesn't spit out the delimiters themselves as extra fields (even though
3484that's the behaviour of L<perlfunc/split> when its pattern contains capturing
3485groups). It's also cheaper not to capture
24863486characters if you don't need to.
24873487
24883488=end original
24893489
2490余計なフィー出しません。
3490(例えそれが捕捉グープ含むとの L<perlfunc/split> の振る舞いで
3491あったとしても) 区切り文字自身を余計なフィールドとして引き出しません。
24913492また不要であれば文字のキャプチャを行わないため低コストです。
24923493
24933494=begin original
24943495
2495Any letters between C<?> and C<:> act as flags modifiers as with
3496Any letters between C<"?"> and C<":"> act as flags modifiers as with
2496C<(?adluimsx-imsx)>. For example,
3497C<(?adluimnsx-imnsx)>. For example,
24973498
24983499=end original
24993500
2500C<?> 及び C<:> の間の文字は C<(?adluimsx-imsx)> のようなフラグ修飾子として
3501C<"?"> 及び C<":"> の間の文字は C<(?adluimnsx-imnsx)> のような
2501動作します。
3502フラグ修飾子として動作します。
25023503例えば、
25033504
25043505 /(?s-i:more.*than).*million/i
25053506
25063507=begin original
25073508
25083509is equivalent to the more verbose
25093510
25103511=end original
25113512
25123513はより冗長に書けば以下と等価です
25133514
25143515 /(?:(?s-i)more.*than).*million/i
25153516
25163517=begin original
25173518
3519Note that any C<()> constructs enclosed within this one will still
3520capture unless the C</n> modifier is in effect.
3521
3522=end original
3523
3524これの中の C<()> 構文は、C</n> が有効でない限りまだ捕捉することに
3525注意してください。
3526
3527=begin original
3528
3529Like the L</(?adlupimnsx-imnsx)> construct, C<aa> and C<"a"> override each
3530other, as do C<xx> and C<"x">. They are not additive. So, doing
3531something like C<(?xx-x:foo)> turns off all C<"x"> behavior for matching
3532C<foo>.
3533
3534=end original
3535
3536L</(?adlupimnsx-imnsx)> 構文と同様、C<xx> と
3537C<"x">と同様に、C<aa> と C<"a"> は互いに上書きします。
3538これらは加法的ではありません。
3539したがって、C<(?xx-x:foo)> のようなことを行うと、
3540C<foo> にマッチングする間、C<"x"> の動作がすべてオフになります。
3541
3542=begin original
3543
25183544Starting in Perl 5.14, a C<"^"> (caret or circumflex accent) immediately
2519after the C<"?"> is a shorthand equivalent to C<d-imsx>. Any positive
3545after the C<"?"> is a shorthand equivalent to C<d-imnsx>. Any positive
25203546flags (except C<"d">) may follow the caret, so
25213547
25223548=end original
25233549
2524Perl 5.14から、C<"^">(キャレット曲折アクセント)がC<"?">のすぐ
3550Perl 5.14 から、C<"^">(キャレットあるいは曲折アクセント)が C<"?"> のすぐ
2525後ろにつくと、C<d-imsx>と同じになります。
3551後ろにつくと、C<d-imnsx> と同じになります。
2526どのような肯定のフラグ(C<"d">以外の)もキャレットに続けることができます;
3552どのような肯定のフラグ(C<"d"> 以外の)もキャレットに続けることができます;
25273553そのため、
25283554
25293555 (?^x:foo)
25303556
25313557=begin original
25323558
25333559is equivalent to
25343560
25353561=end original
25363562
25373563は、以下と同じになります。
25383564
2539 (?x-ims:foo)
3565 (?x-imns:foo)
25403566
25413567=begin original
25423568
25433569The caret tells Perl that this cluster doesn't inherit the flags of any
2544surrounding pattern, but uses the system defaults (C<d-imsx>),
3570surrounding pattern, but uses the system defaults (C<d-imnsx>),
25453571modified by any flags specified.
25463572
25473573=end original
25483574
25493575キャレットは、Perlにこのクラスターはパターンの周りのどのフラグも
2550引き継がずに、代わりに、システムのデフォルトのフラグ(C<d-imsx>)
3576引き継がずに、代わりに、システムのデフォルトのフラグ (C<d-imnsx>)
25513577を使うことを教えます; 指定されている他のフラグによって変更されます。
25523578
25533579=begin original
25543580
25553581The caret allows for simpler stringification of compiled regular
25563582expressions. These look like
25573583
25583584=end original
25593585
25603586キャレットはより簡単なコンパイルされた正規表現の文字列化をすることが
25613587できます。次のものは
25623588
25633589 (?^:pattern)
25643590
25653591=begin original
25663592
25673593with any non-default flags appearing between the caret and the colon.
25683594A test that looks at such stringification thus doesn't need to have the
25693595system default flags hard-coded in it, just the caret. If new flags are
25703596added to Perl, the meaning of the caret's expansion will change to include
25713597the default for those flags, so the test will still work, unchanged.
25723598
25733599=end original
25743600
25753601キャレットとコロンの間には、デフォルトでないフラグがありません。
25763602このような文字列化を見るテストには、したがって、システムのデフォルトのフラグを
25773603その中にハードコードする必要はなく、ただキャレットを使います。新しいフラグが
25783604Perlに追加されたら、キャレットを展開した意味はそれらのフラグのためのデフォルトを
25793605含むように変更されます; そのために、このテストは、それでも何も変えずに
25803606動くでしょう。
25813607
25823608=begin original
25833609
25843610Specifying a negative flag after the caret is an error, as the flag is
25853611redundant.
25863612
25873613=end original
25883614
25893615キャレットの後ろに否定のフラグを付けると、余計なフラグであるとして、
25903616エラーになります。
25913617
25923618=begin original
25933619
25943620Mnemonic for C<(?^...)>: A fresh beginning since the usual use of a caret is
25953621to match at the beginning.
25963622
25973623=end original
25983624
25993625C<(?^...)>の覚え方: 新鮮な開始; 通常のキャレットの使い方は文字列の開始の
26003626マッチなので。
26013627
26023628=item C<(?|pattern)>
26033629X<(?|)> X<Branch reset>
26043630
26053631=begin original
26063632
26073633This is the "branch reset" pattern, which has the special property
26083634that the capture groups are numbered from the same starting point
26093635in each alternation branch. It is available starting from perl 5.10.0.
26103636
26113637=end original
26123638
26133639これは各代替分岐において捕捉グループを同じ番号から始める特殊な
26143640属性を持っている、「ブランチリセット(branch reset)」パターンです。
26153641これは perl 5.10.0 から提供されています。
26163642
26173643=begin original
26183644
26193645Capture groups are numbered from left to right, but inside this
26203646construct the numbering is restarted for each branch.
26213647
26223648=end original
26233649
26243650捕捉グループは左から右へと番号が振られますが、この構成子の内側では
26253651各分岐毎に番号はリセットされます。
26263652
26273653=begin original
26283654
26293655The numbering within each branch will be as normal, and any groups
26303656following this construct will be numbered as though the construct
26313657contained only one branch, that being the one with the most capture
26323658groups in it.
26333659
26343660=end original
26353661
26363662各分岐内での番号付けは通常通りに行われ、この構成子の後に続くグループは
26373663その中で捕捉グループが一番多かった分岐のみが
26383664格納されていたかのように番号付けされていきます。
26393665
26403666=begin original
26413667
26423668This construct is useful when you want to capture one of a
26433669number of alternative matches.
26443670
26453671=end original
26463672
26473673この構成子はいくつかの代替マッチングの1つを捕捉したいときに便利です。
26483674
26493675=begin original
26503676
26513677Consider the following pattern. The numbers underneath show in
26523678which group the captured content will be stored.
26533679
26543680=end original
26553681
26563682以下のパターンを想像してみてください。
26573683下側の番号は内容の格納されるグループを示します。
26583684
2659 # before ---------------branch-reset----------- after
3685 # before ---------------branch-reset----------- after
26603686 / ( a ) (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x
2661 # 1 2 2 3 2 3 4
3687 # 1 2 2 3 2 3 4
26623688
26633689=begin original
26643690
2665Be careful when using the branch reset pattern in combination with
3691Be careful when using the branch reset pattern in combination with
2666named captures. Named captures are implemented as being aliases to
3692named captures. Named captures are implemented as being aliases to
26673693numbered groups holding the captures, and that interferes with the
26683694implementation of the branch reset pattern. If you are using named
26693695captures in a branch reset pattern, it's best to use the same names,
26703696in the same order, in each of the alternations:
26713697
26723698=end original
26733699
26743700名前付き捕捉と枝リセットパターンを組み合わせて使うときには注意してください。
26753701名前付き捕捉は捕捉を保持している番号付きグループへの別名として
26763702実装されていて、枝リセットパターンの実装を妨害します。
26773703枝リセットパターンで名前付き捕捉を使うときは、それぞれの代替で
26783704同じ名前を同じ順番で使うのが最良です:
26793705
26803706 /(?| (?<a> x ) (?<b> y )
26813707 | (?<a> z ) (?<b> w )) /x
26823708
26833709=begin original
26843710
26853711Not doing so may lead to surprises:
26863712
26873713=end original
26883714
26893715そうしないと驚くことになります:
26903716
26913717 "12" =~ /(?| (?<a> \d+ ) | (?<b> \D+))/x;
2692 say $+ {a}; # Prints '12'
3718 say $+{a}; # Prints '12'
2693 say $+ {b}; # *Also* prints '12'.
3719 say $+{b}; # *Also* prints '12'.
26943720
26953721=begin original
26963722
26973723The problem here is that both the group named C<< a >> and the group
26983724named C<< b >> are aliases for the group belonging to C<< $1 >>.
26993725
27003726=end original
27013727
27023728ここでの問題は、C<< a >> という名前のグループと C<< b >> という名前の
27033729が両方ともグループ C<< $1 >> への別名であることです。
27043730
2705=item Look-Around Assertions
3731=item Lookaround Assertions
27063732X<look-around assertion> X<lookaround assertion> X<look-around> X<lookaround>
27073733
27083734=begin original
27093735
2710Look-around assertions are zero-width patterns which match a specific
3736Lookaround assertions are zero-width patterns which match a specific
27113737pattern without including it in C<$&>. Positive assertions match when
27123738their subpattern matches, negative assertions match when their subpattern
2713fails. Look-behind matches text up to the current match position,
3739fails. Lookbehind matches text up to the current match position,
2714look-ahead matches text following the current match position.
3740lookahead matches text following the current match position.
27153741
27163742=end original
27173743
27183744先読み及び後読みの言明(assertion)は C<$&> の中に
27193745含めない特定のパターンにマッチングするゼロ幅のパターンです。
27203746正の言明はその部分パターンがマッチングしたときにマッチングし、
27213747負の言明はその部分パターンが失敗したときにマッチングします。
27223748後読みのマッチングは今のマッチング位置までのテキストにマッチングし、
27233749先読みの言明は今のマッチング位置の先にあるテキストにマッチングします。
27243750
27253751=over 4
27263752
27273753=item C<(?=pattern)>
2728X<(?=)> X<look-ahead, positive> X<lookahead, positive>
27293754
3755=item C<(*pla:pattern)>
3756
3757=item C<(*positive_lookahead:pattern)>
3758X<(?=)>
3759X<(*pla>
3760X<(*positive_lookahead>
3761X<look-ahead, positive> X<lookahead, positive>
3762
27303763=begin original
27313764
2732A zero-width positive look-ahead assertion. For example, C</\w+(?=\t)/>
3765A zero-width positive lookahead assertion. For example, C</\w+(?=\t)/>
27333766matches a word followed by a tab, without including the tab in C<$&>.
27343767
27353768=end original
27363769
27373770ゼロ幅の正の先読み言明。
27383771例えば、C</\w+(?=\t)/> はタブが続く単語にマッチングしますが、タブは
27393772C<$&> に含まれません。
27403773
3774=begin original
3775
3776The alphabetic forms are experimental; using them yields a warning in the
3777C<experimental::alpha_assertions> category.
3778
3779=end original
3780
3781英字形式は実験的です; これらを使うと
3782C<experimental::alpha_assertions> カテゴリの警告が出ます。
3783
27413784=item C<(?!pattern)>
2742X<(?!)> X<look-ahead, negative> X<lookahead, negative>
27433785
3786=item C<(*nla:pattern)>
3787
3788=item C<(*negative_lookahead:pattern)>
3789X<(?!)>
3790X<(*nla>
3791X<(*negative_lookahead>
3792X<look-ahead, negative> X<lookahead, negative>
3793
27443794=begin original
27453795
2746A zero-width negative look-ahead assertion. For example C</foo(?!bar)/>
3796A zero-width negative lookahead assertion. For example C</foo(?!bar)/>
27473797matches any occurrence of "foo" that isn't followed by "bar". Note
2748however that look-ahead and look-behind are NOT the same thing. You cannot
3798however that lookahead and lookbehind are NOT the same thing. You cannot
2749use this for look-behind.
3799use this for lookbehind.
27503800
27513801=end original
27523802
27533803ゼロ幅の負の先読み言明。
27543804例えば C</foo(?!bar)/> は "bar" が続かない全ての "foo" にマッチングします。
27553805しかしながら先読みと後読みは同じ物では ない点に注意してください。
27563806これを後読みに使うことはできません。
27573807
27583808=begin original
27593809
27603810If you are looking for a "bar" that isn't preceded by a "foo", C</(?!foo)bar/>
27613811will not do what you want. That's because the C<(?!foo)> is just saying that
27623812the next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" will
2763match. Use look-behind instead (see below).
3813match. Use lookbehind instead (see below).
27643814
27653815=end original
27663816
27673817もし "foo" が前にない "bar" を探しているのなら、
27683818C</(?!foo)bar/> では欲しい物にはなりません。
27693819なぜなら C<(?!foo)> は次のものが "foo" ではないとだけいっているのです --
27703820そしてそうではなく、そこには "bar" があるので、"foobar" はマッチングします。
27713821(後述の) 後方参照を使ってください。
27723822
2773=item C<(?<=pattern)> C<\K>
3823=begin original
2774X<(?<=)> X<look-behind, positive> X<lookbehind, positive> X<\K>
27753824
3825The alphabetic forms are experimental; using them yields a warning in the
3826C<experimental::alpha_assertions> category.
3827
3828=end original
3829
3830英字形式は実験的です; これらを使うと
3831C<experimental::alpha_assertions> カテゴリの警告が出ます。
3832
3833=item C<(?<=pattern)>
3834
3835=item C<\K>
3836
3837=item C<(*plb:pattern)>
3838
3839=item C<(*positive_lookbehind:pattern)>
3840X<(?<=)>
3841X<(*plb>
3842X<(*positive_lookbehind>
3843X<look-behind, positive> X<lookbehind, positive> X<\K>
3844
27763845=begin original
27773846
2778A zero-width positive look-behind assertion. For example, C</(?<=\t)\w+/>
3847A zero-width positive lookbehind assertion. For example, C</(?<=\t)\w+/>
27793848matches a word that follows a tab, without including the tab in C<$&>.
2780Works only for fixed-width look-behind.
3849Works only for fixed-width lookbehind.
27813850
27823851=end original
27833852
27843853ゼロ幅の正の後読みの言明。
27853854例えば、C</(?<=\t)\w+/> は
27863855タブに続く単語にマッチングしますが、タブは $& に 含まれません。
27873856固定幅の後読みのみが動作します。
27883857
27893858=begin original
27903859
2791There is a special form of this construct, called C<\K>, which causes the
3860There is a special form of this construct, called C<\K> (available since
3861Perl 5.10.0), which causes the
27923862regex engine to "keep" everything it had matched prior to the C<\K> and
27933863not include it in C<$&>. This effectively provides variable-length
2794look-behind. The use of C<\K> inside of another look-around assertion
3864lookbehind. The use of C<\K> inside of another lookaround assertion
27953865is allowed, but the behaviour is currently not well defined.
27963866
27973867=end original
27983868
2799C<\K> というこの構成子の特殊な形式もあります
3869(Perl 5.10.0 から利用可能な) C<\K> というこの構成子の特殊な形式もあります;
28003870これは正規表現エンジンに対してそれが C<\K> までにマッチングした
28013871すべてのものを"取っておいて"、C<$&> には含めないようにさせます。
28023872これは事実上可変長の後読みを提供します。
28033873他の先読み及び後読みの言明の中での利用も可能ですが、その振る舞いは
28043874今のところあまり定義されていません。
28053875
28063876=begin original
28073877
28083878For various reasons C<\K> may be significantly more efficient than the
28093879equivalent C<< (?<=...) >> construct, and it is especially useful in
28103880situations where you want to efficiently remove something following
28113881something else in a string. For instance
28123882
28133883=end original
28143884
28153885いくつかの理由から、C<\K> は等価な C<< (?<=...) >>
28163886構成子より非常に効率的で、文字列の中で何かに続いている何かを効率的に
28173887取り除きたいようなシチュエーションで効果的に役立ちます。
28183888例えば
28193889
28203890 s/(foo)bar/$1/g;
28213891
28223892=begin original
28233893
28243894can be rewritten as the much more efficient
28253895
28263896=end original
28273897
28283898次のようにより効率的に書き直せます
28293899
28303900 s/foo\Kbar//g;
28313901
3902=begin original
3903
3904The alphabetic forms (not including C<\K> are experimental; using them
3905yields a warning in the C<experimental::alpha_assertions> category.
3906
3907=end original
3908
3909(C<\K> を除く) 英字形式は実験的です; これらを使うと
3910C<experimental::alpha_assertions> カテゴリの警告が出ます。
3911
28323912=item C<(?<!pattern)>
2833X<(?<!)> X<look-behind, negative> X<lookbehind, negative>
28343913
3914=item C<(*nlb:pattern)>
3915
3916=item C<(*negative_lookbehind:pattern)>
3917X<(?<!)>
3918X<(*nlb>
3919X<(*negative_lookbehind>
3920X<look-behind, negative> X<lookbehind, negative>
3921
28353922=begin original
28363923
2837A zero-width negative look-behind assertion. For example C</(?<!bar)foo/>
3924A zero-width negative lookbehind assertion. For example C</(?<!bar)foo/>
28383925matches any occurrence of "foo" that does not follow "bar". Works
2839only for fixed-width look-behind.
3926only for fixed-width lookbehind.
28403927
28413928=end original
28423929
28433930ゼロ幅の負の後読みの言明。
28443931例えば C</(?<!bar)foo/> は "bar" に続いていない任意の "foo" に
28453932マッチングします。
28463933固定幅の後読みのみが動作します。
28473934
2848=back
3935=begin original
28493936
2850=item C<(?'NAME'pattern)>
3937The alphabetic forms are experimental; using them yields a warning in the
3938C<experimental::alpha_assertions> category.
28513939
3940=end original
3941
3942英字形式は実験的です; これらを使うと
3943C<experimental::alpha_assertions> カテゴリの警告が出ます。
3944
3945=back
3946
28523947=item C<< (?<NAME>pattern) >>
3948
3949=item C<(?'NAME'pattern)>
28533950X<< (?<NAME>) >> X<(?'NAME')> X<named capture> X<capture>
28543951
28553952=begin original
28563953
28573954A named capture group. Identical in every respect to normal capturing
28583955parentheses C<()> but for the additional fact that the group
28593956can be referred to by name in various regular expression
28603957constructs (like C<\g{NAME}>) and can be accessed by name
28613958after a successful match via C<%+> or C<%->. See L<perlvar>
28623959for more details on the C<%+> and C<%-> hashes.
28633960
28643961=end original
28653962
28663963名前付の捕捉グループ。
28673964通常のキャプチャかっこ C<()> と同様ですがそれに加えて、
28683965グループは(C<\g{NAME}> のように) 様々な正規表現構文で名前で参照でき、
28693966マッチングに成功したあと C<%+> を C<%-> を使って名前によって
28703967アクセスできます。
28713968C<%+> 及び C<%-> ハッシュに関する詳細は L<perlvar> を
28723969参照してください。
28733970
28743971=begin original
28753972
2876If multiple distinct capture groups have the same name then the
3973If multiple distinct capture groups have the same name, then
2877$+{NAME} will refer to the leftmost defined group in the match.
3974C<$+{NAME}> will refer to the leftmost defined group in the match.
28783975
28793976=end original
28803977
28813978複数の異なる捕捉グループが同じ名前を持っていたときには
2882$+{NAME} はマッチングの中で一番左で定義されたグループを参照します。
3979C<$+{NAME}> はマッチングの中で一番左で定義されたグループを参照します。
28833980
28843981=begin original
28853982
28863983The forms C<(?'NAME'pattern)> and C<< (?<NAME>pattern) >> are equivalent.
28873984
28883985=end original
28893986
28903987二つの形式 C<(?'NAME'pattern)> 及び C<< (?<NAME>pattern) >> は等価です。
28913988
28923989=begin original
28933990
28943991B<NOTE:> While the notation of this construct is the same as the similar
28953992function in .NET regexes, the behavior is not. In Perl the groups are
28963993numbered sequentially regardless of being named or not. Thus in the
28973994pattern
28983995
28993996=end original
29003997
29013998B<補足:> これを構成する記法は 類似していている .NET での正規表現と
29023999同じですが、振る舞いは異なります。
29034000Perl ではグループは名前がついているかどうかにかかわらず順番に番号が
29044001振られます。
29054002従って次のパターンにおいて
29064003
29074004 /(x)(?<foo>y)(z)/
29084005
29094006=begin original
29104007
2911$+{foo} will be the same as $2, and $3 will contain 'z' instead of
4008C<$+{I<foo>}> will be the same as C<$2>, and C<$3> will contain 'z' instead of
29124009the opposite which is what a .NET regex hacker might expect.
29134010
29144011=end original
29154012
2916$+{foo} は $2 と同じであり、$3 には .NET 正規表現に
4013C<$+{I<foo>}>C<$2> と同じであり、C<$3> には .NET 正規表現に
29174014慣れた人が予測するのとは異なり 'z' が含まれます。
29184015
29194016=begin original
29204017
2921Currently NAME is restricted to simple identifiers only.
4018Currently I<NAME> is restricted to simple identifiers only.
29224019In other words, it must match C</^[_A-Za-z][_A-Za-z0-9]*\z/> or
29234020its Unicode extension (see L<utf8>),
29244021though it isn't extended by the locale (see L<perllocale>).
29254022
29264023=end original
29274024
2928現在のところ NAME はシンプルな識別子のみに制限されています。
4025現在のところ I<NAME> はシンプルな識別子のみに制限されています。
29294026言い換えると、C</^[_A-Za-z][_A-Za-z0-9]*\z/> または
29304027その Unicode 拡張にマッチングしなければなりません
29314028(L<utf8> も参照); しかしロケールでは拡張されません
29324029(L<perllocale> 参照)。
29334030
29344031=begin original
29354032
29364033B<NOTE:> In order to make things easier for programmers with experience
29374034with the Python or PCRE regex engines, the pattern C<< (?PE<lt>NAMEE<gt>pattern) >>
29384035may be used instead of C<< (?<NAME>pattern) >>; however this form does not
29394036support the use of single quotes as a delimiter for the name.
29404037
29414038=end original
29424039
29434040B<補足:> Python や PCRE 正規表現エンジンになれたプログラマが
29444041楽になるように、C<< (?<NAME>pattern) >> の代わりに
29454042C<< (?PE<lt>NAMEE<gt>pattern) >> のパターンを使うことも
29464043できます; しかしこの形式は名前のデリミタとして
29474044シングルクォートの使用はサポートされていません。
29484045
29494046=item C<< \k<NAME> >>
29504047
29514048=item C<< \k'NAME' >>
29524049
29534050=begin original
29544051
29554052Named backreference. Similar to numeric backreferences, except that
29564053the group is designated by name and not number. If multiple groups
29574054have the same name then it refers to the leftmost defined group in
29584055the current match.
29594056
29604057=end original
29614058
29624059名前による後方参照。
29634060数値によってではなく名前によってグループを指定する点を除いて、名前による
29644061後方参照と似ています。
29654062もし同じ名前の複数のグループがあったときには現在のマッチングで
29664063一番左に定義されているグループを参照します。
29674064
29684065=begin original
29694066
29704067It is an error to refer to a name not defined by a C<< (?<NAME>) >>
29714068earlier in the pattern.
29724069
29734070=end original
29744071
29754072パターン内で C<< (?<NAME>) >> によって定義されていない名前を
29764073参照するとエラーになります。
29774074
29784075=begin original
29794076
29804077Both forms are equivalent.
29814078
29824079=end original
29834080
29844081両方の形式とも等価です。
29854082
29864083=begin original
29874084
29884085B<NOTE:> In order to make things easier for programmers with experience
29894086with the Python or PCRE regex engines, the pattern C<< (?P=NAME) >>
29904087may be used instead of C<< \k<NAME> >>.
29914088
29924089=end original
29934090
29944091B<補足:> Python や PCRE 正規表現エンジンになれたプログラマが楽に
29954092なるように、C<< \k<NAME> >> の代わりに
29964093C<< (?P=NAME) >> のパターンを使うこともできます。
29974094
29984095=item C<(?{ code })>
29994096X<(?{})> X<regex, code in> X<regexp, code in> X<regular expression, code in>
30004097
30014098=begin original
30024099
3003B<WARNING>: This extended regular expression feature is considered
4100B<WARNING>: Using this feature safely requires that you understand its
3004experimental, and may be changed without notice. Code executed that
4101limitations. Code executed that has side effects may not perform identically
3005has side effects may not perform identically from version to version
4102from version to version due to the effect of future optimisations in the regex
3006due to the effect of future optimisations in the regex engine.
4103engine. For more information on this, see L</Embedded Code Execution
4104Frequency>.
30074105
30084106=end original
30094107
3010B<警告>: この拡張正規表現の機能は実験的なもと考えられおり、
4108B<警告>: この機能を安全に使うに、そ制限につい理解することが必要です。
3011また通知なしに変更されるかもしれません。
30124109副作用を持つコードの実行は今後の正規表現エンジンの最適化の影響で
30134110バージョン間で必ずしも同じになるとは限らないでしょう。
4111これに関するさらなる情報については、L</Embedded Code Execution Frequency> を
4112参照してください。
30144113
30154114=begin original
30164115
3017This zero-width assertion evaluates any embedded Perl code. It
4116This zero-width assertion executes any embedded Perl code. It always
3018always succeeds, and its C<code> is not interpolated. Currently,
4117succeeds, and its return value is set as C<$^R>.
3019the rules to determine where the C<code> ends are somewhat convoluted.
30204118
30214119=end original
30224120
3023このゼロ幅アサーションは埋め込まれた任意の Perl コードを評価します。
4121このゼロ幅アサーションは埋め込まれた任意の Perl コードを実行します。
3024これは常に(正規表現として)成功し、その C<code> は埋め込まれません
4122これは常に(正規表現として)成功し、返り値は C<$^R> に設定されま
3025今のところ、C<code> が終わる場所を認識するルールは少々複雑です。
30264123
30274124=begin original
30284125
3029This feature can be used together with the special variable C<$^N> to
4126In literal patterns, the code is parsed at the same time as the
3030capture the results of submatches in variables without having to keep
4127surrounding code. While within the pattern, control is passed temporarily
3031track of the number of nested parentheses. For example:
4128back to the perl parser, until the logically-balancing closing brace is
4129encountered. This is similar to the way that an array index expression in
4130a literal string is handled, for example
30324131
30334132=end original
30344133
3035この機能では一緒にネストしたかっこの数を数えなくとも1つ前
4134リテラルなパターンではこのコードは周りコードと同時にパースされます。
3036マッチング結果をキャプチャ特殊変数 C<$^N> を使うとがきます。
4135のパターンの中は、
3037例えば:
4136論理的にバランスが取れる閉じかっこが現れるまで、
4137制御文字は一時的に perl パーサーに渡されます。
4138これはリテラル文字列の中の配列添字表現の扱われ方と似ています; 例えば:
30384139
3039 $_ = "The brown fox jumps over the lazy dog";
4140 "abc$array[ 1 + f('[') + g()]def"
3040 /the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i;
3041 print "color = $color, animal = $animal\n";
30424141
30434142=begin original
30444143
3045Inside the C<(?{...})> block, C<$_> refers to the string the regular
4144In particular, braces do not need to be balanced:
4145
4146=end original
4147
4148特に、中かっこはバランスが取れている必要はありません:
4149
4150 s/abc(?{ f('{'); })/def/
4151
4152=begin original
4153
4154Even in a pattern that is interpolated and compiled at run-time, literal
4155code blocks will be compiled once, at perl compile time; the following
4156prints "ABCD":
4157
4158=end original
4159
4160実行時に展開されてコンパイルされるパターンの中であっても、
4161リテラルなコードブロックは perl のコンパイル時に一度だけコンパイルされます;
4162次のものは "ABCD" と表示されます:
4163
4164 print "D";
4165 my $qr = qr/(?{ BEGIN { print "A" } })/;
4166 my $foo = "foo";
4167 /$foo$qr(?{ BEGIN { print "B" } })/;
4168 BEGIN { print "C" }
4169
4170=begin original
4171
4172In patterns where the text of the code is derived from run-time
4173information rather than appearing literally in a source code /pattern/,
4174the code is compiled at the same time that the pattern is compiled, and
4175for reasons of security, C<use re 'eval'> must be in scope. This is to
4176stop user-supplied patterns containing code snippets from being
4177executable.
4178
4179=end original
4180
4181コードのテキストがソースコードの /pattern/ としてリテラルに現れるのではなく、
4182実行時の情報から派生したものであるパターンでは、
4183コードはパターンがコンパイルされるのと同時にコンパイルされ、
4184セキュリティー上の理由により、C<use re 'eval'> が
4185スコープ内になければなりません。
4186これは、実行可能なコード片を含む、ユーザーが提供したパターンを止めるためです。
4187
4188=begin original
4189
4190In situations where you need to enable this with C<use re 'eval'>, you should
4191also have taint checking enabled. Better yet, use the carefully
4192constrained evaluation within a Safe compartment. See L<perlsec> for
4193details about both these mechanisms.
4194
4195=end original
4196
4197C<use re 'eval'> でこれを有効にする必要がある場合、
4198汚染チェックも有効にするべきです。
4199出来れば、Safe 区画の中で注意深く制限された評価を使ってください。
4200これら両方の機構に関する詳細については L<perlsec> を参照してください。
4201
4202=begin original
4203
4204From the viewpoint of parsing, lexical variable scope and closures,
4205
4206=end original
4207
4208パース、レキシカル変数スコープ、クロージャの観点から、
4209
4210 /AAA(?{ BBB })CCC/
4211
4212=begin original
4213
4214behaves approximately like
4215
4216=end original
4217
4218はおよそ次のように振る舞います:
4219
4220 /AAA/ && do { BBB } && /CCC/
4221
4222=begin original
4223
4224Similarly,
4225
4226=end original
4227
4228同様に、
4229
4230 qr/AAA(?{ BBB })CCC/
4231
4232=begin original
4233
4234behaves approximately like
4235
4236=end original
4237
4238はおよそ次のように振る舞います:
4239
4240 sub { /AAA/ && do { BBB } && /CCC/ }
4241
4242=begin original
4243
4244In particular:
4245
4246=end original
4247
4248特に:
4249
4250 { my $i = 1; $r = qr/(?{ print $i })/ }
4251 my $i = 2;
4252 /$r/; # prints "1"
4253
4254=begin original
4255
4256Inside a C<(?{...})> block, C<$_> refers to the string the regular
30464257expression is matching against. You can also use C<pos()> to know what is
30474258the current position of matching within this string.
30484259
30494260=end original
30504261
30514262C<(?{...})> ブロックの中では C<$_> は正規表現をマッチングさせている文字列を
30524263参照します。
30534264C<pos()> を使ってこの文字列で現在のマッチング位置を知ることもできます。
30544265
30554266=begin original
30564267
3057The C<code> is properly scoped in the following sense: If the assertion
4268The code block introduces a new scope from the perspective of lexical
3058is backtracked (compare L<"Backtracking">), all changes introduced after
4269variable declarations, but B<not> from the perspective of C<local> and
3059C<local>ization are undone, so that
4270similar localizing behaviours. So later code blocks within the same
4271pattern will still see the values which were localized in earlier blocks.
4272These accumulated localizations are undone either at the end of a
4273successful match, or if the assertion is backtracked (compare
4274L</"Backtracking">). For example,
30604275
30614276=end original
30624277
3063C<code> は次感じで適切にスコプを持ちます: もしアサーションが
4278コードブロックは、C<local> や同様カル化の振る舞いの観点 B<ではなく>
3064バックトラックされている(L<"Backtracking"> 参照)なら、
4279レキシカル変数宣言観点での新しいスコープを導入します。
3065C<local> されなかた後の全の変更つまり
4280って、同じパターンで後に出てくるコードブロックは
4281前に出てきたローカル化された値が見えるままです。
4282これらの蓄積されたローカル化は、マッチングが成功するか、
4283アサートがバックトラックした時点で巻き戻されます
4284(L</"Backtracking"> と比較してください)。
4285例えば:
30664286
30674287 $_ = 'a' x 8;
30684288 m<
30694289 (?{ $cnt = 0 }) # Initialize $cnt.
30704290 (
30714291 a
30724292 (?{
30734293 local $cnt = $cnt + 1; # Update $cnt,
30744294 # backtracking-safe.
30754295 })
30764296 )*
30774297 aaaa
30784298 (?{ $res = $cnt }) # On success copy to
30794299 # non-localized location.
30804300 >x;
30814301
30824302=begin original
30834303
3084will set C<$res = 4>. Note that after the match, C<$cnt> returns to the globally
4304will initially increment C<$cnt> up to 8; then during backtracking, its
3085introduced value, because the scopes that restrict C<local> operators
4305value will be unwound back to 4, which is the value assigned to C<$res>.
3086are unwound.
4306At the end of the regex execution, C<$cnt> will be wound back to its initial
4307value of 0.
30874308
30884309=end original
30894310
3090は C<$res = 4> を設定します
4311これまず C<$cnt> 8でインクリメントされま;
3091チング後で C<$cnt> はグローバルに設定された値を返します; なぜなら
4312それからバクトラック間に、この値は 4 まで巻き戻され
3092C<local> 演算子で制限されたスコープは巻き戻されるためです。
4313その値が C<$res> に代入されす。
4314正規表現実行の最後では、$cnt は初期値である 0 に巻き戻ります。
30934315
30944316=begin original
30954317
3096This assertion may be used as a C<(?(condition)yes-pattern|no-pattern)>
4318This assertion may be used as the condition in a
3097switch. If I<not> used in this way, the result of evaluation of
3098C<code> is put into the special variable C<$^R>. This happens
3099immediately, so C<$^R> can be used from other C<(?{ code })> assertions
3100inside the same regular expression.
31014319
31024320=end original
31034321
3104このアサーションは C<(?(condition)yes-pattern|no-pattern)> スイッチとして
4322このアサーションは条件として:
3105使われるかもしれません。
4324 (?(condition)yes-pattern|no-pattern)
4325
4326=begin original
4327
4328switch. If I<not> used in this way, the result of evaluation of C<code>
4329is put into the special variable C<$^R>. This happens immediately, so
4330C<$^R> can be used from other C<(?{ code })> assertions inside the same
4331regular expression.
4332
4333=end original
4334
4335スイッチとして使われるかもしれません。
31064336この方法で使われI<なかった>のなら、C<code> の評価結果は特殊変数 C<$^R> に
31074337おかれます。
31084338これはすぐに行われるので C<$^R> は同じ正規表現内の他の C<?{ code })>
31094339アサーションで使うことができます。
31104340
31114341=begin original
31124342
31134343The assignment to C<$^R> above is properly localized, so the old
31144344value of C<$^R> is restored if the assertion is backtracked; compare
3115L<"Backtracking">.
4345L</"Backtracking">.
31164346
31174347=end original
31184348
31194349この C<$^R> への設定は適切にlocal化されるため、C<$^R> の古い値は
3120バックトラックしたときには復元されます; L<"Backtracking"> を
4350バックトラックしたときには復元されます; L</"Backtracking"> を
31214351見てください。
31224352
31234353=begin original
31244354
3125For reasons of security, this construct is forbidden if the regular
4355Note that the special variable C<$^N> is particularly useful with code
3126expression involves run-time interpolation of variables, unless the
4356blocks to capture the results of submatches in variables without having to
3127perilous C<use re 'eval'> pragma has been used (see L<re>), or the
4357keep track of the number of nested parentheses. For example:
3128variables contain results of the C<qr//> operator (see
3129L<perlop/"qr/STRINGE<sol>msixpodual">).
31304358
31314359=end original
31324360
3133セキュリティ的な理由により、正規表現を実行時に変数から構築することは、
4361特殊変数 C<$^N> は、一緒にネストしたかっこの数を数えずに一つ前の
3134危険な C<use re 'eval'> プラグが使われてい(L<re> 参照)か
4362ッチング結果を捕捉すコードブロックで特に有用です。
3135変数が C<qr//> 演算子(L<perlop/"qr/STRINGE<sol>msixpodual"> 参照)の結果を
3136含んでいる時以外は拒否されます。
3137
3138=begin original
3139
3140This restriction is due to the wide-spread and remarkably convenient
3141custom of using run-time determined strings as patterns. For example:
3142
3143=end original
3144
3145この制限は、実行時に決まる文字列をパターンとして使う、とても広まっていて
3146とても便利な風習のためのものです。
31474363例えば:
31484364
3149 $re = <>;
4365 $_ = "The brown fox jumps over the lazy dog";
3150 chomp $re;
4366 /the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i;
3151 $string =~ /$re/;
4367 print "color = $color, animal = $animal\n";
31524368
4369=item C<(??{ code })>
4370X<(??{})>
4371X<regex, postponed> X<regexp, postponed> X<regular expression, postponed>
4372
31534373=begin original
31544374
3155Before Perl knew how to execute interpolated code within a pattern,
4375B<WARNING>: Using this feature safely requires that you understand its
3156this operation was completely safe from a security point of view,
4376limitations. Code executed that has side effects may not perform
3157although it could raise an exception from an illegal pattern. If
4377identically from version to version due to the effect of future
3158you turn on the C<use re 'eval'>, though, it is no longer secure,
4378optimisations in the regex engine. For more information on this, see
3159so you should only do so if you are also using taint checking.
4379L</Embedded Code Execution Frequency>.
3160Better yet, use the carefully constrained evaluation within a Safe
3161compartment. See L<perlsec> for details about both these mechanisms.
31624380
31634381=end original
31644382
3165Perl がパターン中にあるコード実行する方法を知る前はの操作は不正な
4383B<警告>: 機能安全に使うには、その制限について理解することが必要です。
3166パターンで例外を発生させはしますがセキュリティ的な視点で完全に安全でした。
4384副作用を持つコドの実行は今後の正規表現エジンの最適化の影響
3167 C<use re 'eval'> を有効しているのら、これもはやセキュア
4385バージョン間で必ずも同じになると限らないしょう。
3168ありません; そして汚染チェックを使っているときだけ行うべきで
4386これるさらなる情報については、L</Embedded Code Execution Frequency> を
3169より良い方法としては、Safe の区画内で注意深制限れた評価を
4387参照してくい。
3170使うべきでしょう。
3171この双方のメカニズムについての詳細は L<perlsec> を参照してください。
31724388
31734389=begin original
31744390
3175B<WARNING>: Use of lexical (C<my>) variables in these blocks is
4391This is a "postponed" regular subexpression. It behaves in I<exactly> the
3176broken. The result is unpredictable and will make perl unstable. The
4392same way as a C<(?{ code })> code block as described above, except that
3177workaround is to use global (C<our>) variables.
4393its return value, rather than being assigned to C<$^R>, is treated as a
4394pattern, compiled if it's a string (or used as-is if its a qr// object),
4395then matched as if it were inserted instead of this construct.
31784396
31794397=end original
31804398
3181B<警告>: これらのブロックでのレキシカル (C<my>) 変数の使用ています。
4399これは「先送りさた」正規部分表現です。
3182結果不確定で、perl を不安定します。
4400これ上述の C<(?{ code })> コードブロックと I<正確> 同じように
3183回避方法グローバル (C<our>) 変数を使うことす。
4401振る舞いますが、その返り値C<$^R> に代入されるのはなく、
4402パターンとして扱われ、
4403それが文字列の場合はコンパイルされ(あるいは qr// オブジェクトの場合は
4404そのまま使われ)、それからこの構文の代わりに挿入されていたかのように
4405マッチングします。
31844406
31854407=begin original
31864408
3187B<WARNING>: In perl 5.12.x and earlier, the regex engine
4409During the matching of this sub-pattern, it has its own set of
3188was not re-entrant, so interpolated code could not
4410captures which are valid during the sub-match, but are discarded once
3189safely invoke the regex engine either directly with
4411control returns to the main pattern. For example, the following matches,
3190C<m//> or C<s///>), or indirectly with functions such as
4412with the inner pattern capturing "B" and matching "BB", while the outer
3191C<split>. Invoking the regex engine in these blocks would make perl
4413pattern captures "A";
3192unstable.
31934414
31944415=end original
31954416
3196B<警告>: Perl 5.12.x 以前では、正規表現エは再入可能ではない
4417副パターのマッチ副マッチングの間有効な独自の捕捉グループを
3197埋め込れたコドかは C<m//> たは C<s///> を使って直接的にでも
4418持ちすが、一旦制御が主パタンに戻ると捨てす。
3198C<split> ような関数を使って間接的にも安全は呼び出せません。
4419例えば、次マッチングは、内側のパターン "B" と "BB" マッチングし、
3199これらブロックで正規表現エジンを起動すると perl が不安定になります
4420一方外側パター "A" を捕捉します;
32004421
3201=item C<(??{ code })>
4422 my $inner = '(.)\1';
3202X<(??{})>
4423 "ABBA" =~ /^(.)(??{ $inner })\1/;
3203X<regex, postponed> X<regexp, postponed> X<regular expression, postponed>
4424 print $1; # prints "A";
32044425
32054426=begin original
32064427
3207B<WARNING>: This extended regular expression feature is considered
4428Note that this means that there is no way for the inner pattern to refer
3208experimental, and may be changed without notice. Code executed that
4429to a capture group defined outside. (The code block itself can use C<$1>,
3209has side effects may not perform identically from version to version
4430I<etc>., to refer to the enclosing pattern's capture groups.) Thus, although
3210due to the effect of future optimisations in the regex engine.
32114431
32124432=end original
32134433
3214B<警告>: こ拡張正規表現の機能は実験的なものと考えらており、
4434内側パターンが外側で定義さた捕捉グループを参照する方法は
3215また通知変更されるかもれません
4435いこと注意てください
3216副作用を持つコードの実行は今後の正規表現エンジンの最適化の影響で
3217バージョン間で必ずしも同じになるとは限らないでしょう。
3218
3219=begin original
3220
3221This is a "postponed" regular subexpression. The C<code> is evaluated
3222at run time, at the moment this subexpression may match. The result
3223of evaluation is considered a regular expression and matched as
3224if it were inserted instead of this construct. Note that this means
3225that the contents of capture groups defined inside an eval'ed pattern
3226are not available outside of the pattern, and vice versa, there is no
3227way for the inner pattern returned from the code block to refer to a
3228capture group defined outside. (The code block itself can use C<$1>, etc.,
3229to refer to the enclosing pattern's capture groups.) Thus,
3230
3231=end original
3232
3233これは「先送りされた」正規部分表現です。
3234C<code> は実行時に評価され、そのときにこの部分表現にマッチングさせます。
3235評価の結果は正規表現として受け取られ、この構成子の代わりに
3236入れられていたかのようにマッチングされます。
3237これは eval されたパターン内部で定義された捕捉グループの内容はパターンの
3238外側では提供されず、そしてその逆も同様になる点に注意してください;
3239コードブロックから返された内側のパターンが
3240外側で定義された捕捉グループを参照する方法はありません。
32414436(コードブロック自体は、内側のパターンの捕捉グループを参照するために
32424437C<$1> などを使えます。)
32434438従って:
32444439
32454440 ('a' x 100)=~/(??{'(.)' x 100})/
32464441
32474442=begin original
32484443
3249B<will> match, it will B<not> set $1.
4444I<will> match, it will I<not> set C<$1> on exit.
32504445
32514446=end original
32524447
3253これはマッチング B<します> が、$1 は設定 B<されません>。
4448これはマッチング I<します> が、終了時に C<$1> は設定 I<されません>。
32544449
32554450=begin original
32564451
3257The C<code> is not interpolated. As before, the rules to determine
3258where the C<code> ends are currently somewhat convoluted.
3259
3260=end original
3261
3262C<code> は埋め込まれません。
3263先の時と同様に C<code> が終了していると決定するルールは少々複雑です。
3264
3265=begin original
3266
32674452The following pattern matches a parenthesized group:
32684453
32694454=end original
32704455
32714456次のパターンはかっこで囲まれたグループにマッチングします:
32724457
32734458 $re = qr{
32744459 \(
32754460 (?:
32764461 (?> [^()]+ ) # Non-parens without backtracking
32774462 |
32784463 (??{ $re }) # Group with matching parens
32794464 )*
32804465 \)
32814466 }x;
32824467
32834468=begin original
32844469
3285See also C<(?PARNO)> for a different, more efficient way to accomplish
4470See also
4471L<C<(?I<PARNO>)>|/(?PARNO) (?-PARNO) (?+PARNO) (?R) (?0)>
4472for a different, more efficient way to accomplish
32864473the same task.
32874474
32884475=end original
32894476
3290同じタスクを行う別の、より効率的な方法として C<(?PARNO)> も
4477同じタスクを行う別の、より効率的な方法として
4478L<C<(?I<PARNO>)>|/(?PARNO) (?-PARNO) (?+PARNO) (?R) (?0)> も
32914479参照してください。
32924480
32934481=begin original
32944482
3295For reasons of security, this construct is forbidden if the regular
4483Executing a postponed regular expression too many times without
3296expression involves run-time interpolation of variables, unless the
4484consuming any input string will also result in a fatal error. The depth
3297perilous C<use re 'eval'> pragma has been used (see L<re>), or the
4485at which that happens is compiled into perl, so it can be changed with a
3298variables contain results of the C<qr//> operator (see
4486custom build.
3299L<perlop/"qrE<sol>STRINGE<sol>msixpodual">).
33004487
33014488=end original
33024489
3303セキュリティ的理由によ正規表現を実行時に変数から構築することは、
4490入力を消費しい多すぎる先送された正規表現を実行するのも
3304危険 C<use re 'eval'> プグマが使われている(L<re> 参照)か
4491致命的ーとなります。
3305変数C<qr//> 演算子(L<perlop/"qr/STRING/imosx"> 参照)結果を
4492これ起きる深度は perl にコンパイルされているで、カスタムビルドで
3306含んでいる時以外は拒否されます。
4493を変更できます。
33074494
3308=begin original
4495=item C<(?I<PARNO>)> C<(?-I<PARNO>)> C<(?+I<PARNO>)> C<(?R)> C<(?0)>
4496X<(?PARNO)> X<(?1)> X<(?R)> X<(?0)> X<(?-1)> X<(?+1)> X<(?-PARNO)> X<(?+PARNO)>
4497X<regex, recursive> X<regexp, recursive> X<regular expression, recursive>
4498X<regex, relative recursion> X<GOSUB> X<GOSTART>
33094499
3310In perl 5.12.x and earlier, because the regex engine was not re-entrant,
3311delayed code could not safely invoke the regex engine either directly with
3312C<m//> or C<s///>), or indirectly with functions such as C<split>.
3313
3314=end original
3315
3316perl 5.12.x 以前では、Perl の正規表現エンジンは再入可能ではないので、
3317遅延されたコードからは C<m//> または C<s///> を使って直接的にでも
3318C<split> のような関数を使って間接的にでも安全には呼び出せません。
3319
33204500=begin original
33214501
3322Recursing deeper than 50 times without consuming any input string will
4502Recursive subpattern. Treat the contents of a given capture buffer in the
3323result in a fatal error. The maximum depth is compiled into perl, so
4503current pattern as an independent subpattern and attempt to match it at
3324changing it requires a custom build.
4504the current position in the string. Information about capture state from
4505the caller for things like backreferences is available to the subpattern,
4506but capture buffers set by the subpattern are not visible to the caller.
33254507
33264508=end original
33274509
3328入力を消費しない 50 回を超える深い再帰は致命的なエラとなります
4510再帰部分パタ
3329最大深度は perl にコンイルされているで、これを変更するには特別に
4511現在のターン与えらた捕捉バッファの内容独立した
3330ビルドする必要があります。
4512部分パターンとして扱って、
4513文字列の現在の位置でマッチングしようとします。
4514後方参照のような呼び出し元からの捕捉状態に関する情報は
4515部分パターンで利用可能ですが、
4516部分パターンで設定された捕捉バッファは呼び出し元には見えません。
33314517
3332=item C<(?PARNO)> C<(?-PARNO)> C<(?+PARNO)> C<(?R)> C<(?0)>
3333X<(?PARNO)> X<(?1)> X<(?R)> X<(?0)> X<(?-1)> X<(?+1)> X<(?-PARNO)> X<(?+PARNO)>
3334X<regex, recursive> X<regexp, recursive> X<regular expression, recursive>
3335X<regex, relative recursion>
3336
33374518=begin original
33384519
3339Similar to C<(??{ code })> except it does not involve compiling any code,
4520Similar to C<(??{ code })> except that it does not involve executing any
3340instead it treats the contents of a capture group as an independent
4521code or potentially compiling a returned pattern string; instead it treats
3341pattern that must match at the current position. Capture groups
4522the part of the current pattern contained within a specified capture group
3342contained by the pattern will have the value as determined by the
4523as an independent pattern that must match at the current position. Also
3343outermost recursion.
4524different is the treatment of capture buffers, unlike C<(??{ code })>
4525recursive patterns have access to their caller's match state, so one can
4526use backreferences safely.
33444527
33454528=end original
33464529
3347コードのコンパイルを伴わなずその代わりに捕捉グループの内容を現在の位置で
4530C<(??{ code })> と似ていますが
3348マッチングすべき独立したパターンて扱う、C<(??{ code })> と似た機能です。
4531コードの実行を伴なわず、返されたパターン文字列をコンパイルもません;
3349パターン内包されている捕捉グループは一番外側再帰として
4532その代わり、指定され捕捉グループに含まれる現在パターンの一部を、
3350決定されるという価値があります。
4533現在の位置でマッチングすべき独立したパターンして扱います。
4534また、捕捉バッファの扱いも異なります;
4535C<(??{ code })> と異なり、再帰パターンはその呼び出し元のマッチング
4536状態にアクセスすることが出来るので、安全に後方参照を使えます。
33514537
33524538=begin original
33534539
3354PARNO is a sequence of digits (not starting with 0) whose value reflects
4540I<PARNO> is a sequence of digits (not starting with 0) whose value reflects
33554541the paren-number of the capture group to recurse to. C<(?R)> recurses to
33564542the beginning of the whole pattern. C<(?0)> is an alternate syntax for
3357C<(?R)>. If PARNO is preceded by a plus or minus sign then it is assumed
4543C<(?R)>. If I<PARNO> is preceded by a plus or minus sign then it is assumed
33584544to be relative, with negative numbers indicating preceding capture groups
33594545and positive ones following. Thus C<(?-1)> refers to the most recently
33604546declared group, and C<(?+1)> indicates the next group to be declared.
33614547Note that the counting for relative recursion differs from that of
33624548relative backreferences, in that with recursion unclosed groups B<are>
33634549included.
33644550
33654551=end original
33664552
3367PARNO はその値が再帰させる捕捉グループのかっこ番号を反映する一連の
4553I<PARNO> はその値が再帰させる捕捉グループのかっこ番号を反映する一連の
33684554数字からなります(そして 0 からは始まりません)。
33694555C<(?R)> はパターン全体の最初から再帰します。
33704556C<(?0)> は C<(?R)> の別の構文です。
3371PARNO の前に正符号または負符号がついていた場合には相対的な位置として
4557I<PARNO> の前に正符号または負符号がついていた場合には相対的な位置として
33724558使われます; 負数であれば前の捕捉グループを、正数であれば続く
33734559捕捉グループを示します。
33744560従って C<(?-1)> は一番最近宣言されたグループを参照し、C<(?+1)> は次に
33754561宣言されるグループを参照します。
33764562相対再帰の数え方は相対後方参照とは違って、グループに閉じていない再帰は
33774563含まB<れる>ことに注意してください,
33784564
33794565=begin original
33804566
3381The following pattern matches a function foo() which may contain
4567The following pattern matches a function C<foo()> which may contain
33824568balanced parentheses as the argument.
33834569
33844570=end original
33854571
33864572以下のパターンは引数にバランスのとれたかっこを含んでいるかもしれない関数
3387foo() にマッチングします。
4573C<foo()> にマッチングします。
33884574
33894575 $re = qr{ ( # paren group 1 (full function)
33904576 foo
33914577 ( # paren group 2 (parens)
33924578 \(
33934579 ( # paren group 3 (contents of parens)
33944580 (?:
33954581 (?> [^()]+ ) # Non-parens without backtracking
33964582 |
33974583 (?2) # Recurse to start of paren group 2
33984584 )*
33994585 )
34004586 \)
34014587 )
34024588 )
34034589 }x;
34044590
34054591=begin original
34064592
34074593If the pattern was used as follows
34084594
34094595=end original
34104596
34114597このパターンを以下のように使うと,
34124598
34134599 'foo(bar(baz)+baz(bop))'=~/$re/
34144600 and print "\$1 = $1\n",
34154601 "\$2 = $2\n",
34164602 "\$3 = $3\n";
34174603
34184604=begin original
34194605
34204606the output produced should be the following:
34214607
34224608=end original
34234609
34244610次のように出力されます:
34254611
34264612 $1 = foo(bar(baz)+baz(bop))
34274613 $2 = (bar(baz)+baz(bop))
34284614 $3 = bar(baz)+baz(bop)
34294615
34304616=begin original
34314617
34324618If there is no corresponding capture group defined, then it is a
3433fatal error. Recursing deeper than 50 times without consuming any input
4619fatal error. Recursing deeply without consuming any input string will
3434string will also result in a fatal error. The maximum depth is compiled
4620also result in a fatal error. The depth at which that happens is
3435into perl, so changing it requires a custom build.
4621compiled into perl, so it can be changed with a custom build.
34364622
34374623=end original
34384624
34394625もし対応する捕捉グループが定義されていなかったときには致命的な
34404626エラーとなります。
3441入力を消費しない 50 回を超える深い再帰も致命的なエラーとなります。
4627入力を消費しない深い再帰も致命的なエラーとなります。
3442最大深度は perl にコンパイルされているので、これを変更するには特別に
4628これが起きる深度は perl にコンパイルされているので、カスタムビルドで
3443ビルドする必要があります。
4629これを変更できます。
34444630
34454631=begin original
34464632
34474633The following shows how using negative indexing can make it
34484634easier to embed recursive patterns inside of a C<qr//> construct
34494635for later use:
34504636
34514637=end original
34524638
34534639以下に後で使うパターンのために、C<qr//> 構成子内で再帰を埋め込むのに
34544640負数の参照を使うとどのように容易になるかを示します:
34554641
34564642 my $parens = qr/(\((?:[^()]++|(?-1))*+\))/;
3457 if (/foo $parens \s+ + \s+ bar $parens/x) {
4643 if (/foo $parens \s+ \+ \s+ bar $parens/x) {
34584644 # do something here...
34594645 }
34604646
34614647=begin original
34624648
34634649B<Note> that this pattern does not behave the same way as the equivalent
34644650PCRE or Python construct of the same form. In Perl you can backtrack into
34654651a recursed group, in PCRE and Python the recursed into group is treated
34664652as atomic. Also, modifiers are resolved at compile time, so constructs
3467like (?i:(?1)) or (?:(?i)(?1)) do not affect how the sub-pattern will
4653like C<(?i:(?1))> or C<(?:(?i)(?1))> do not affect how the sub-pattern will
34684654be processed.
34694655
34704656=end original
34714657
34724658B<補足> このパターンは PCRE や Python での等価な形式の構成子と同じように
34734659振る舞うわけではありません。
34744660Perl においては再帰グループの中にバックトラックできますが、PCRE や
34754661Python ではグループへの再帰はアトミックに扱われます。
3476また、修飾子はコンパイル時に解決されるので、(?i:(?1)) や
4662また、修飾子はコンパイル時に解決されるので、C<(?i:(?1))>
3477(?:(?i)(?1)) といった構成子はサブパターンがどのように処理されたかに
4663C<(?:(?i)(?1))> といった構成子はサブパターンがどのように処理されたかに
34784664影響されません。
34794665
34804666=item C<(?&NAME)>
34814667X<(?&NAME)>
34824668
34834669=begin original
34844670
3485Recurse to a named subpattern. Identical to C<(?PARNO)> except that the
4671Recurse to a named subpattern. Identical to C<(?I<PARNO>)> except that the
34864672parenthesis to recurse to is determined by name. If multiple parentheses have
34874673the same name, then it recurses to the leftmost.
34884674
34894675=end original
34904676
34914677名前付きサブパターンへの再帰。
3492再帰するかっこが名前によって決定される点以外は C<(?PARNO)> と等価です。
4678再帰するかっこが名前によって決定される点以外は C<(?I<PARNO>)> と等価です。
34934679もし複数のかっこで同じ名前を持っていた場合には一番左のものに再帰します。
34944680
34954681=begin original
34964682
34974683It is an error to refer to a name that is not declared somewhere in the
34984684pattern.
34994685
35004686=end original
35014687
35024688パターンのどこでも宣言されていない名前の参照はエラーになります。
35034689
35044690=begin original
35054691
35064692B<NOTE:> In order to make things easier for programmers with experience
35074693with the Python or PCRE regex engines the pattern C<< (?P>NAME) >>
35084694may be used instead of C<< (?&NAME) >>.
35094695
35104696=end original
35114697
35124698B<補足:> Python または PCRE 正規表現エンジンに慣れているプログラマが
35134699簡単になるように C<< (?&NAME) >> の代わりに C<< (?P>NANE) >> を使うことも
35144700できます。
35154701
35164702=item C<(?(condition)yes-pattern|no-pattern)>
35174703X<(?()>
35184704
35194705=item C<(?(condition)yes-pattern)>
35204706
35214707=begin original
35224708
35234709Conditional expression. Matches C<yes-pattern> if C<condition> yields
35244710a true value, matches C<no-pattern> otherwise. A missing pattern always
35254711matches.
35264712
35274713=end original
35284714
35294715条件付き式。
35304716C<condition> が真なら C<yes-pattern> にマッチングし、さもなければ
35314717C<no-pattern> にマッチングします。
35324718パターンがなければ常にマッチングします。
35334719
35344720=begin original
35354721
3536C<(condition)> should be either an integer in
4722C<(condition)> should be one of:
3537parentheses (which is valid if the corresponding pair of parentheses
3538matched), a look-ahead/look-behind/evaluate zero-width assertion, a
4724=end original
3539name in angle brackets or single quotes (which is valid if a group
3540with the given name matched), or the special symbol (R) (true when
4726C<(condition)> は次のいずれかです:
3541evaluated inside of recursion or eval). Additionally the R may be
4728=over 4
4729
4730=item an integer in parentheses
4731
4732(かっこでくるまれた数値)
4733
4734=begin original
4735
4736(which is valid if the corresponding pair of parentheses
4737matched);
4738
4739=end original
4740
4741(対応するかっこ対がマッチングしたときに有効);
4742
4743=item a lookahead/lookbehind/evaluate zero-width assertion;
4744
4745(先読み/後読み/ゼロ幅で評価される言明)
4746
4747=item a name in angle brackets or single quotes
4748
4749(角かっこもしくはシングルクォートでくるまれた名前)
4750
4751=begin original
4752
4753(which is valid if a group with the given name matched);
4754
4755=end original
4756
4757(その名前のグループがマッチングしたときに有効);
4758
4759=item the special symbol C<(R)>
4760
4761(特殊なシンボル C<(R)>)
4762
4763=begin original
4764
4765(true when evaluated inside of recursion or eval). Additionally the
4766C<"R"> may be
35424767followed by a number, (which will be true when evaluated when recursing
35434768inside of the appropriate group), or by C<&NAME>, in which case it will
35444769be true only when evaluated during recursion in the named group.
35454770
35464771=end original
35474772
3548C<(condition)> かっこくるまた数値(対応すかっこ対が
4773(再帰また eval 内評価さていときに真)。
3549マッチングしときに有効)、先読み/後読み/ゼロ幅で評価される言明、角かっこ
4774加えて C<"R"> には数字(対応するループ内で再帰ているときに)、もしくは
3550もしくはシングルクォートでくるまれた名前(その名前のグループが
3551マッチングしたときに有効)、特殊なシンボル (R) (再帰または eval 内で
3552評価されているときに真)のいずれかです。
3553加えて R には数字(対応するグループ内で再帰しているときに真)、もしくは
35544775C<&NAME>、こちらの時はその名前のグループで再帰している時にのみ真、を
35554776続けることもできます。
35564777
4778=back
4779
35574780=begin original
35584781
35594782Here's a summary of the possible predicates:
35604783
35614784=end original
35624785
35634786可能な述語の要約を次に示します:
35644787
35654788=over 4
35664789
3567=item (1) (2) ...
4790=item C<(1)> C<(2)> ...
35684791
35694792=begin original
35704793
35714794Checks if the numbered capturing group has matched something.
4795Full syntax: C<< (?(1)then|else) >>
35724796
35734797=end original
35744798
35754799その番号の捕捉グループが何かにマッチングしたかどうかを調べます。
4800完全な文法: C<< (?(1)then|else) >>
35764801
3577=item (<NAME>) ('NAME')
4802=item C<(E<lt>I<NAME>E<gt>)> C<('I<NAME>')>
35784803
35794804=begin original
35804805
35814806Checks if a group with the given name has matched something.
4807Full syntax: C<< (?(<name>)then|else) >>
35824808
35834809=end original
35844810
35854811その名前のグループが何かにマッチングしたかどうかを調べます。
4812完全な文法: C<< (?(<name>)then|else) >>
35864813
3587=item (?=...) (?!...) (?<=...) (?<!...)
4814=item C<(?=...)> C<(?!...)> C<(?<=...)> C<(?<!...)>
35884815
35894816=begin original
35904817
3591Checks whether the pattern matches (or does not match, for the '!'
4818Checks whether the pattern matches (or does not match, for the C<"!">
35924819variants).
4820Full syntax: C<< (?(?=lookahead)then|else) >>
35934821
35944822=end original
35954823
3596パターンがマッチングするか (あるいは '!' 版はマッチングしないか) を
4824パターンがマッチングするか (あるいは C<"!"> 版はマッチングしないか) を
35974825チェックします。
4826完全な文法: C<< (?(?=lookahead)then|else) >>
35984827
3599=item (?{ CODE })
4828=item C<(?{ I<CODE> })>
36004829
36014830=begin original
36024831
36034832Treats the return value of the code block as the condition.
4833Full syntax: C<< (?(?{ code })then|else) >>
36044834
36054835=end original
36064836
36074837コードブロックの返り値を条件として扱います。
4838完全な文法: C<< (?(?{ code })then|else) >>
36084839
3609=item (R)
4840=item C<(R)>
36104841
36114842=begin original
36124843
36134844Checks if the expression has been evaluated inside of recursion.
4845Full syntax: C<< (?(R)then|else) >>
36144846
36154847=end original
36164848
36174849式が再帰の中で評価されているかどうかを調べます。
4850完全な文法: C<< (?(R)then|else) >>
36184851
3619=item (R1) (R2) ...
4852=item C<(R1)> C<(R2)> ...
36204853
36214854=begin original
36224855
36234856Checks if the expression has been evaluated while executing directly
36244857inside of the n-th capture group. This check is the regex equivalent of
36254858
36264859=end original
36274860
36284861式がその n 番目の捕捉グループのすぐ内側で実行されているかどうかを調べます。
36294862これは次のものと等価な正規表現です
36304863
36314864 if ((caller(0))[3] eq 'subname') { ... }
36324865
36334866=begin original
36344867
36354868In other words, it does not check the full recursion stack.
36364869
36374870=end original
36384871
36394872言い換えると、これは完全な再帰スタックを調べるわけではありません。
36404873
3641=item (R&NAME)
4874=begin original
36424875
4876Full syntax: C<< (?(R1)then|else) >>
4877
4878=end original
4879
4880完全な文法: C<< (?(R1)then|else) >>
4881
4882=item C<(R&I<NAME>)>
4883
36434884=begin original
36444885
36454886Similar to C<(R1)>, this predicate checks to see if we're executing
36464887directly inside of the leftmost group with a given name (this is the same
3647logic used by C<(?&NAME)> to disambiguate). It does not check the full
4888logic used by C<(?&I<NAME>)> to disambiguate). It does not check the full
36484889stack, but only the name of the innermost active recursion.
4890Full syntax: C<< (?(R&name)then|else) >>
36494891
36504892=end original
36514893
36524894C<(R1)> と似ていて、この述語はその名前のつけられている一番左のグループの
3653すぐ内側で実行されているかどうかをしらべます(一番左は C<(?NAME)> と
4895すぐ内側で実行されているかどうかをしらべます(一番左は C<(?&I<NAME>)> と
36544896同じロジックです)。
36554897これは完全なスタックを調べずに、一番内部のアクティブな再帰の名前だけを
36564898調べます。
4899完全な文法: C<< (?(R&name)then|else) >>
36574900
3658=item (DEFINE)
4901=item C<(DEFINE)>
36594902
36604903=begin original
36614904
36624905In this case, the yes-pattern is never directly executed, and no
36634906no-pattern is allowed. Similar in spirit to C<(?{0})> but more efficient.
36644907See below for details.
4908Full syntax: C<< (?(DEFINE)definitions...) >>
36654909
36664910=end original
36674911
36684912この場合において、yes-pattern は直接は実行されず、no-pattern は
36694913許可されていません。
36704914C<(?{0})> と似ていますがより効率的です。
36714915詳細は次のようになります。
4916完全な文法: C<< (?(DEFINE)definitions...) >>
36724917
36734918=back
36744919
36754920=begin original
36764921
36774922For example:
36784923
36794924=end original
36804925
36814926例:
36824927
36834928 m{ ( \( )?
36844929 [^()]+
36854930 (?(1) \) )
36864931 }x
36874932
36884933=begin original
36894934
36904935matches a chunk of non-parentheses, possibly included in parentheses
36914936themselves.
36924937
36934938=end original
36944939
36954940これはかっこ以外からなる固まりかかっこの中にあるそれらにマッチングします。
36964941
36974942=begin original
36984943
36994944A special form is the C<(DEFINE)> predicate, which never executes its
37004945yes-pattern directly, and does not allow a no-pattern. This allows one to
37014946define subpatterns which will be executed only by the recursion mechanism.
37024947This way, you can define a set of regular expression rules that can be
37034948bundled into any pattern you choose.
37044949
37054950=end original
37064951
37074952C<(DEFINE)> は特殊な形式で、これはその yes-pattern を直接は実行せず、
37084953no-pattern も許可していません。
37094954これは再帰メカニズムの中で利用することでのみ実行されるサブパターンの
37104955定義を許可します。
37114956これによって、選んだパターンと一緒に正規表現ルールを定義できます。
37124957
37134958=begin original
37144959
37154960It is recommended that for this usage you put the DEFINE block at the
37164961end of the pattern, and that you name any subpatterns defined within it.
37174962
37184963=end original
37194964
37204965この使い方において、DEFINE ブロックはパターンの最後におくこと、
37214966そしてそこで定義する全てのサブパターンに名前をつけることが
37224967推奨されています。
37234968
37244969=begin original
37254970
37264971Also, it's worth noting that patterns defined this way probably will
3727not be as efficient, as the optimiser is not very clever about
4972not be as efficient, as the optimizer is not very clever about
37284973handling them.
37294974
37304975=end original
37314976
37324977また、この方法によって定義されるパターンはその処理に関してそんなに
37334978賢い訳ではないので効率的でないことに価値は何もないでしょう。
37344979
37354980=begin original
37364981
37374982An example of how this might be used is as follows:
37384983
37394984=end original
37404985
37414986これをどのように使うかの例を次に示します:
37424987
37434988 /(?<NAME>(?&NAME_PAT))(?<ADDR>(?&ADDRESS_PAT))
37444989 (?(DEFINE)
37454990 (?<NAME_PAT>....)
3746 (?<ADRESS_PAT>....)
4991 (?<ADDRESS_PAT>....)
37474992 )/x
37484993
37494994=begin original
37504995
37514996Note that capture groups matched inside of recursion are not accessible
37524997after the recursion returns, so the extra layer of capturing groups is
37534998necessary. Thus C<$+{NAME_PAT}> would not be defined even though
37544999C<$+{NAME}> would be.
37555000
37565001=end original
37575002
37585003再帰の内側でマッチングした捕捉グループは再帰から戻った後には
37595004アクセスできないため、余分な捕捉グループの
37605005レイヤは必要な点に注意してください。
37615006従って C<$+{NAME}> が定義されていても C<$+{NAME_PAT}> は定義されません。
37625007
37635008=begin original
37645009
37655010Finally, keep in mind that subpatterns created inside a DEFINE block
37665011count towards the absolute and relative number of captures, so this:
37675012
37685013=end original
37695014
37705015最後に、DEFINE ブロックの内側で作られた副パターンは捕捉の絶対及び
37715016相対番号で数えることに注意してください; 従ってこうすると:
37725017
37735018 my @captures = "a" =~ /(.) # First capture
37745019 (?(DEFINE)
37755020 (?<EXAMPLE> 1 ) # Second capture
37765021 )/x;
37775022 say scalar @captures;
37785023
37795024=begin original
37805025
37815026Will output 2, not 1. This is particularly important if you intend to
37825027compile the definitions with the C<qr//> operator, and later
37835028interpolate them in another pattern.
37845029
37855030=end original
37865031
378750321 ではなく 2 を出力します。
37885033これは、C<qr//> 演算子で定義をコンパイルして、
37895034後で他のパターンの中で展開することを意図している場合に特に重要です。
37905035
37915036=item C<< (?>pattern) >>
5037
5038=item C<< (*atomic:pattern) >>
5039X<(?E<gt>pattern)>
5040X<(*atomic>
37925041X<backtrack> X<backtracking> X<atomic> X<possessive>
37935042
37945043=begin original
37955044
37965045An "independent" subexpression, one which matches the substring
37975046that a I<standalone> C<pattern> would match if anchored at the given
37985047position, and it matches I<nothing other than this substring>. This
37995048construct is useful for optimizations of what would otherwise be
3800"eternal" matches, because it will not backtrack (see L<"Backtracking">).
5049"eternal" matches, because it will not backtrack (see L</"Backtracking">).
38015050It may also be useful in places where the "grab all you can, and do not
38025051give anything back" semantic is desirable.
38035052
38045053=end original
38055054
38065055「独立した」部分式、I<スタンドアロンの> C<pattern> がその場所に
38075056固定されてマッチングする部分文字列にマッチングし、
38085057I<その文字列以外にはなにも>マッチングしません。
38095058この構成子は他の"外部"マッチングになる最適化に便利です;
3810なぜならこれはバックトラックしないためです(L<"Backtracking"> 参照)。
5059なぜならこれはバックトラックしないためです(L</"Backtracking"> 参照)。
38115060これは "できる限りを取り込んで、後は戻らない"セマンティクスが
38125061必要な場所でも便利です。
38135062
38145063=begin original
38155064
38165065For example: C<< ^(?>a*)ab >> will never match, since C<< (?>a*) >>
38175066(anchored at the beginning of string, as above) will match I<all>
3818characters C<a> at the beginning of string, leaving no C<a> for
5067characters C<"a"> at the beginning of string, leaving no C<"a"> for
38195068C<ab> to match. In contrast, C<a*ab> will match the same as C<a+b>,
38205069since the match of the subgroup C<a*> is influenced by the following
3821group C<ab> (see L<"Backtracking">). In particular, C<a*> inside
5070group C<ab> (see L</"Backtracking">). In particular, C<a*> inside
38225071C<a*ab> will match fewer characters than a standalone C<a*>, since
38235072this makes the tail match.
38245073
38255074=end original
38265075
38275076例: C<< ^(?>a*)ab >> は何もマッチングしません、
38285077なぜなら C<< (?>a*) >> (前述のように、文字列の開始で固定されます)は
3829文字列のはじめにある全ての文字 C<a> にマッチングし、
5078文字列のはじめにある全ての文字 C<"a"> にマッチングし、
3830C<ab> のマッチングのための C<a> を残さないためです。
5079C<ab> のマッチングのための C<"a"> を残さないためです。
38315080対照的に、C<a*ab> は C<a+b> と同じようにマッチングします、
38325081これはサブグループ C<a*> のマッチングは次のグループ C<ab> の影響を
3833受けるためです (L<"Backtracking"> 参照)。
5082受けるためです (L</"Backtracking"> 参照)。
38345083特に、C<a*ab> の中の C<a*> は単独の C<a*> より短い文字にマッチングします;
38355084これによって最後のマッチングが行えるようになります。
38365085
38375086=begin original
38385087
38395088C<< (?>pattern) >> does not disable backtracking altogether once it has
38405089matched. It is still possible to backtrack past the construct, but not
38415090into it. So C<< ((?>a*)|(?>b*))ar >> will still match "bar".
38425091
38435092=end original
38445093
38455094C<< (?>pattern) >> は、一旦マッチングしたら、全くバックトラックを
38465095無効にしません。
38475096未だこの構文の前までバックトラックする可能性はありますが、構文の中に
38485097バックトラックすることはありません。
38495098従って C<< ((?>a*)|(?>b*))ar >> は "bar" にマッチングするままです。
38505099
38515100=begin original
38525101
38535102An effect similar to C<< (?>pattern) >> may be achieved by writing
38545103C<(?=(pattern))\g{-1}>. This matches the same substring as a standalone
38555104C<a+>, and the following C<\g{-1}> eats the matched string; it therefore
38565105makes a zero-length assertion into an analogue of C<< (?>...) >>.
38575106(The difference between these two constructs is that the second one
38585107uses a capturing group, thus shifting ordinals of backreferences
38595108in the rest of a regular expression.)
38605109
38615110=end original
38625111
38635112C<< (?>pattern) >> と似た効果は C<(?=(pattern))\g{-1}> でも達成できます。
38645113これは単独の C<a+> と同じ部分文字列にマッチングし、それに続く C<\g{-1}> が
38655114マッチングした文字列を消費します;
38665115これはゼロ幅の言明が C<< (?>...) >> の類似を作るためです。
38675116(この2つの構成子は後者はグループをキャプチャするため、
38685117それに続く正規表現の残りで後方参照の順序をずらす点で違いがあります。)
38695118
38705119=begin original
38715120
38725121Consider this pattern:
38735122
38745123=end original
38755124
38765125次のパターンを考えてみてください:
38775126
38785127 m{ \(
38795128 (
38805129 [^()]+ # x+
38815130 |
38825131 \( [^()]* \)
38835132 )+
38845133 \)
38855134 }x
38865135
38875136=begin original
38885137
38895138That will efficiently match a nonempty group with matching parentheses
38905139two levels deep or less. However, if there is no such group, it
38915140will take virtually forever on a long string. That's because there
38925141are so many different ways to split a long string into several
38935142substrings. This is what C<(.+)+> is doing, and C<(.+)+> is similar
38945143to a subpattern of the above pattern. Consider how the pattern
38955144above detects no-match on C<((()aaaaaaaaaaaaaaaaaa> in several
38965145seconds, but that each extra letter doubles this time. This
38975146exponential performance will make it appear that your program has
38985147hung. However, a tiny change to this pattern
38995148
39005149=end original
39015150
39025151これは 2 段階までのかっこでくるまれた空でないグループに効率的に
39035152マッチングします。
39045153しかしながら、これはマッチングするグループがなかったときに長い
39055154文字列においてはほとんど永遠に戻りません。
39065155これは長い文字列をいくつかの部分文字列に分解する方法がいくつもあるためです。
39075156これは C<(.+)+> が行うことでもあり、C<(.+)+> は このパターンの
39085157部分パターンと似ています。
39095158このパターンが C<((()aaaaaaaaaaaaaaaaaa> にはマッチングしないことを
39105159どうやって検出するかを少し考えてみましょう、
39115160しかしここでは余計な文字を2倍にしてみます。
39125161この指数的なパフォーマンスはプログラムのハングアップとして表面化します。
39135162しかしながら、このパターンに小さな変更をいれてみます,
39145163
39155164 m{ \(
39165165 (
39175166 (?> [^()]+ ) # change x+ above to (?> x+ )
39185167 |
39195168 \( [^()]* \)
39205169 )+
39215170 \)
39225171 }x
39235172
39245173=begin original
39255174
39265175which uses C<< (?>...) >> matches exactly when the one above does (verifying
39275176this yourself would be a productive exercise), but finishes in a fourth
3928the time when used on a similar string with 1000000 C<a>s. Be aware,
5177the time when used on a similar string with 1000000 C<"a">s. Be aware,
39295178however, that, when this construct is followed by a
39305179quantifier, it currently triggers a warning message under
39315180the C<use warnings> pragma or B<-w> switch saying it
39325181C<"matches null string many times in regex">.
39335182
39345183=end original
39355184
39365185これは上で行っているように C<< (?>...) >> マッチングを
39375186使っています(これは自身で確認してみるとよいでしょう)が、
3938しかし 1000000 個の C<a> からなる似た文字列を使ってみると、4 分の 1 の
5187しかし 1000000 個の C<"a"> からなる似た文字列を使ってみると、4 分の 1 の
39395188時間で完了します。
39405189しかしながら、この構文は量指定子が引き続くと現在のところ
39415190C<use warnings> プラグマまたは B<-w> スイッチの影響下では
39425191C<"matches null string many times in regex">
39435192(正規表現において空文字列に何回もマッチングしました) という警告を
39445193発するでしょう。
39455194
39465195=begin original
39475196
39485197On simple groups, such as the pattern C<< (?> [^()]+ ) >>, a comparable
3949effect may be achieved by negative look-ahead, as in C<[^()]+ (?! [^()] )>.
5198effect may be achieved by negative lookahead, as in C<[^()]+ (?! [^()] )>.
3950This was only 4 times slower on a string with 1000000 C<a>s.
5199This was only 4 times slower on a string with 1000000 C<"a">s.
39515200
39525201=end original
39535202
39545203パターン C<< (?> [^()]+ ) >> のような簡単なグループでは、
39555204比較できる影響は C<[^()]+ (?! [^()] )> のように負の先読みの
39565205言明で達することができます。
3957これは 1000000 個の C<a> からなる文字列において 4 倍だけ遅くなります。
5206これは 1000000 個の C<"a"> からなる文字列において 4 倍だけ遅くなります。
39585207
39595208=begin original
39605209
39615210The "grab all you can, and do not give anything back" semantic is desirable
39625211in many situations where on the first sight a simple C<()*> looks like
39635212the correct solution. Suppose we parse text with comments being delimited
3964by C<#> followed by some optional (horizontal) whitespace. Contrary to
5213by C<"<#ins>"> followed by some optional (horizontal) whitespace. Contrary to
39655214its appearance, C<#[ \t]*> I<is not> the correct subexpression to match
39665215the comment delimiter, because it may "give up" some whitespace if
39675216the remainder of the pattern can be made to match that way. The correct
39685217answer is either one of these:
39695218
39705219=end original
39715220
39725221最初の C<()*> のような正しい解法となる多くの状況において
39735222「できる限りを取り込んで、後は戻らない」セマンティクスが望まれるものです。
3974任意で(水平)空白の続く C<#> によって区切られるコメントのついたテキストの
5223任意で(水平)空白の続く C<"<#ins>"> によって区切られるコメントのついたテキストの
39755224パースを考えてみます。
39765225その出現と対比して、C<#[ \t]*> はコメント区切りにマッチングする
39775226正しい部分式ではありません; なぜならパターンの残りがそれのマッチングを
39785227作ることができるのならそれはいくつかの空白を「あきらめてしまう」ためです。
39795228正しい回答は以下のいずれかです:
39805229
39815230 (?>#[ \t]*)
39825231 #[ \t]*(?![ \t])
39835232
39845233=begin original
39855234
3986For example, to grab non-empty comments into $1, one should use either
5235For example, to grab non-empty comments into C<$1>, one should use either
39875236one of these:
39885237
39895238=end original
39905239
3991例えば空でないコメントを $1 に取り込むためには次のいずれかを使います:
5240例えば空でないコメントを C<$1> に取り込むためには次のいずれかを使います:
39925241
39935242 / (?> \# [ \t]* ) ( .+ ) /x;
39945243 / \# [ \t]* ( [^ \t] .* ) /x;
39955244
39965245=begin original
39975246
39985247Which one you pick depends on which of these expressions better reflects
39995248the above specification of comments.
40005249
40015250=end original
40025251
40035252選んだ方はコメントの仕様をより適切に反映した式に依存します。
40045253
40055254=begin original
40065255
40075256In some literature this construct is called "atomic matching" or
40085257"possessive matching".
40095258
40105259=end original
40115260
40125261いくつかの書籍においてこの構成子は「アトミックなマッチング」
40135262または「絶対最大量マッチング(possessive matching)」と呼ばれます。
40145263
40155264=begin original
40165265
40175266Possessive quantifiers are equivalent to putting the item they are applied
40185267to inside of one of these constructs. The following equivalences apply:
40195268
40205269=end original
40215270
40225271絶対最大量指定子はそれが適用されている項目をこれらの構成子の中に置くことと
40235272等価です。
40245273以下の等式が適用されます:
40255274
40265275 Quantifier Form Bracketing Form
40275276 --------------- ---------------
40285277 PAT*+ (?>PAT*)
40295278 PAT++ (?>PAT+)
40305279 PAT?+ (?>PAT?)
40315280 PAT{min,max}+ (?>PAT{min,max})
40325281
5282=begin original
5283
5284Nested C<(?E<gt>...)> constructs are not no-ops, even if at first glance
5285they might seem to be. This is because the nested C<(?E<gt>...)> can
5286restrict internal backtracking that otherwise might occur. For example,
5287
5288=end original
5289
5290ネストした C<(?E<gt>...)> 構文は、
5291たとえ一見何もしないように見えても、何もしないものではありません。
5292これは、ネストした C<(?E<gt>...)> は、なければ起きるかもしれない
5293内部バックトラックを制限するからです。
5294例えば:
5295
5296 "abc" =~ /(?>a[bc]*c)/
5297
5298=begin original
5299
5300matches, but
5301
5302=end original
5303
5304これはマッチングしますが:
5305
5306 "abc" =~ /(?>a(?>[bc]*)c)/
5307
5308=begin original
5309
5310does not.
5311
5312=end original
5313
5314これはマッチングしません。
5315
5316=begin original
5317
5318The alphabetic form (C<(*atomic:...)>) is experimental; using it
5319yields a warning in the C<experimental::alpha_assertions> category.
5320
5321=end original
5322
5323英字形式 (C<(*atomic:...)>) は実験的です; これを使うと
5324C<experimental::alpha_assertions> カテゴリの警告が出ます。
5325
5326=item C<(?[ ])>
5327
5328=begin original
5329
5330See L<perlrecharclass/Extended Bracketed Character Classes>.
5331
5332=end original
5333
5334L<perlrecharclass/Extended Bracketed Character Classes> を参照してください。
5335
5336=begin original
5337
5338Note that this feature is currently L<experimental|perlpolicy/experimental>;
5339using it yields a warning in the C<experimental::regex_sets> category.
5340
5341=end original
5342
5343この機能は現在 L<実験的|perlpolicy/experimental> です;
5344これを使うと C<experimental::regex_sets> カテゴリの警告が発生します。
5345
40335346=back
40345347
4035=head2 Special Backtracking Control Verbs
5348=head2 Backtracking
5349X<backtrack> X<backtracking>
40365350
4037(特殊なバックトラック制御記号)
5351(バックトラック)
40385352
40395353=begin original
40405354
4041B<WARNING:> These patterns are experimental and subject to change or
5355NOTE: This section presents an abstract approximation of regular
4042removal in a future version of Perl. Their usage in production code should
5356expression behavior. For a more rigorous (and complicated) view of
4043be noted to avoid problems during upgrades.
5357the rules involved in selecting a match among possible alternatives,
5358see L</Combining RE Pieces>.
40445359
40455360=end original
40465361
4047B<警告:>れらパターンは実験的なものであり、
5362補足: このセクショ正規表現の振る舞いに関する抽象的な概要を
4048Perl の今後のバージョンで変更または削除される可能性があります。
5363説明します。
4049製品コードでこれらを使う際はアレード問題を
5364可能な代替おけるマチンの選択おけルールの厳密な(そして複雑な)
4050避けるために記するべきです
5365は L</Combining RE Pieces> を参照してください
40515366
40525367=begin original
40535368
4054These special patterns are generally of the form C<(*VERB:ARG)>. Unless
5369A fundamental feature of regular expression matching involves the
4055otherwise stated the ARG argument is optional; in some cases, it is
5370notion called I<backtracking>, which is currently used (when needed)
4056forbidden.
5371by all regular non-possessive expression quantifiers, namely C<"*">, C<*?>, C<"+">,
5372C<+?>, C<{n,m}>, and C<{n,m}?>. Backtracking is often optimized
5373internally, but the general principle outlined here is valid.
40575374
40585375=end original
40595376
4060これら特殊パターン C<(*VERB:ARG)> という一般形式を持っています。
5377正規表現マッチング基本的機能に最近(必要であれば)すべの強欲でな
4061ARG が任意であると規定されていいないいくかのケース以外ではそれは
5378表現量指子、まり
4062拒否されます。
5379C<"*">, C<*?>, C<"+">, C<+?>, C<{n,m}>, C<{n,m}?> で
5380使われる I<バックトラッキング> と呼ばれる概念が含まれています。
5381バックトラックはしばしば内部で最適化されますが、ここで概説する一般的な
5382原則は妥当です。
40635383
40645384=begin original
40655385
5386For a regular expression to match, the I<entire> regular expression must
5387match, not just part of it. So if the beginning of a pattern containing a
5388quantifier succeeds in a way that causes later parts in the pattern to
5389fail, the matching engine backs up and recalculates the beginning
5390part--that's why it's called backtracking.
5391
5392=end original
5393
5394正規表現がマッチングする時、その正規表現の一部ではなく、
5395I<全体> がマッチングしなければなりません。
5396そのためもしパターンの前半にパターンの後半部分を失敗させてしまう
5397量指定子が含まれているのなら、マッチングングエンジンはいったん戻って
5398開始位置を再計算します -- これがバックトラッキングと呼ばれる所以です。
5399
5400=begin original
5401
5402Here is an example of backtracking: Let's say you want to find the
5403word following "foo" in the string "Food is on the foo table.":
5404
5405=end original
5406
5407バックトラッキングの例をあげてみます: "Food is on the foo table." という
5408文字列の中で "foo" に続く単語を取り出してください:
5409
5410 $_ = "Food is on the foo table.";
5411 if ( /\b(foo)\s+(\w+)/i ) {
5412 print "$2 follows $1.\n";
5413 }
5414
5415=begin original
5416
5417When the match runs, the first part of the regular expression (C<\b(foo)>)
5418finds a possible match right at the beginning of the string, and loads up
5419C<$1> with "Foo". However, as soon as the matching engine sees that there's
5420no whitespace following the "Foo" that it had saved in C<$1>, it realizes its
5421mistake and starts over again one character after where it had the
5422tentative match. This time it goes all the way until the next occurrence
5423of "foo". The complete regular expression matches this time, and you get
5424the expected output of "table follows foo."
5425
5426=end original
5427
5428マッチングが実行される時、正規表現の最初の部分 (C<\b(foo)>) は開始文字列の
5429右側で可能なマッチングを探します; そして C<$1> に "Foo" をロードします。
5430しかし、すぐにマッチングエンジンは C<$1> に保存した "Foo" の後に空白が
5431無いことを見つけ、それが失敗だったことを検出して仮にマッチングさせた
5432場所の 1 文字後から開始します。
5433この時次の "foo" の出現まで進みます。
5434この時に正規表現は完全にマッチングし、予測した出力 "table follows foo." を
5435得ます。
5436
5437=begin original
5438
5439Sometimes minimal matching can help a lot. Imagine you'd like to match
5440everything between "foo" and "bar". Initially, you write something
5441like this:
5442
5443=end original
5444
5445最小マッチングが役立つこともあります。
5446"foo" と "bar" の間の全てにマッチングしたいと考えてください。
5447最初に、次のように書くかもしれません:
5448
5449 $_ = "The food is under the bar in the barn.";
5450 if ( /foo(.*)bar/ ) {
5451 print "got <$1>\n";
5452 }
5453
5454=begin original
5455
5456Which perhaps unexpectedly yields:
5457
5458=end original
5459
5460しかしこれは考えたのと違う結果となるでしょう:
5461
5462 got <d is under the bar in the >
5463
5464=begin original
5465
5466That's because C<.*> was greedy, so you get everything between the
5467I<first> "foo" and the I<last> "bar". Here it's more effective
5468to use minimal matching to make sure you get the text between a "foo"
5469and the first "bar" thereafter.
5470
5471=end original
5472
5473これは C<.*> が貪欲であり、そのために I<最初の> "foo" と I<最後の>
5474"bar" の間にある全てを取り出してしまいます。
5475次に "foo" とその後の最初の "bar" の間にあるテキストを取り出す
5476最小マッチングを使ったもっと効率的な方法を示します:
5477
5478 if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
5479 got <d is under the >
5480
5481=begin original
5482
5483Here's another example. Let's say you'd like to match a number at the end
5484of a string, and you also want to keep the preceding part of the match.
5485So you write this:
5486
5487=end original
5488
5489別の例も出してみます。
5490文字列の最後にある数字にマッチングさせて、そのマッチングの前の部分も
5491保持させてみましょう。
5492そしてあなたは次のように書くかもしれません。
5493
5494 $_ = "I have 2 numbers: 53147";
5495 if ( /(.*)(\d*)/ ) { # Wrong!
5496 print "Beginning is <$1>, number is <$2>.\n";
5497 }
5498
5499=begin original
5500
5501That won't work at all, because C<.*> was greedy and gobbled up the
5502whole string. As C<\d*> can match on an empty string the complete
5503regular expression matched successfully.
5504
5505=end original
5506
5507これは全く動作しません、なぜなら C<.*> は貪欲であり文字列全体を
5508飲み込んでしまいます。
5509C<\d*> は空の文字列にマッチングできるので正規表現は完全に正常に
5510マッチングします。
5511
5512 Beginning is <I have 2 numbers: 53147>, number is <>.
5513
5514=begin original
5515
5516Here are some variants, most of which don't work:
5517
5518=end original
5519
5520動作しない主なバリエーションをあげておきます:
5521
5522 $_ = "I have 2 numbers: 53147";
5523 @pats = qw{
5524 (.*)(\d*)
5525 (.*)(\d+)
5526 (.*?)(\d*)
5527 (.*?)(\d+)
5528 (.*)(\d+)$
5529 (.*?)(\d+)$
5530 (.*)\b(\d+)$
5531 (.*\D)(\d+)$
5532 };
5533
5534 for $pat (@pats) {
5535 printf "%-12s ", $pat;
5536 if ( /$pat/ ) {
5537 print "<$1> <$2>\n";
5538 } else {
5539 print "FAIL\n";
5540 }
5541 }
5542
5543=begin original
5544
5545That will print out:
5546
5547=end original
5548
5549これらの結果は次のようになります:
5550
5551 (.*)(\d*) <I have 2 numbers: 53147> <>
5552 (.*)(\d+) <I have 2 numbers: 5314> <7>
5553 (.*?)(\d*) <> <>
5554 (.*?)(\d+) <I have > <2>
5555 (.*)(\d+)$ <I have 2 numbers: 5314> <7>
5556 (.*?)(\d+)$ <I have 2 numbers: > <53147>
5557 (.*)\b(\d+)$ <I have 2 numbers: > <53147>
5558 (.*\D)(\d+)$ <I have 2 numbers: > <53147>
5559
5560=begin original
5561
5562As you see, this can be a bit tricky. It's important to realize that a
5563regular expression is merely a set of assertions that gives a definition
5564of success. There may be 0, 1, or several different ways that the
5565definition might succeed against a particular string. And if there are
5566multiple ways it might succeed, you need to understand backtracking to
5567know which variety of success you will achieve.
5568
5569=end original
5570
5571このように、これは幾分トリッキーです。
5572重要なのは正規表現は成功の定義を定める主張の集合にすぎないことを
5573認識することです。
5574特定の文字列で成功となる定義には 0, 1 または複数の違ったやり方が存在します。
5575そしてもし成功する複数の方法が存在するのなら成功したうちのどれが目的と
5576するものなのかを知るためにバックトラッキングを理解しておく必要があります。
5577
5578=begin original
5579
5580When using lookahead assertions and negations, this can all get even
5581trickier. Imagine you'd like to find a sequence of non-digits not
5582followed by "123". You might try to write that as
5583
5584=end original
5585
5586前読みの言明及び否定を使っている時にはこれはますますトリッキーになります。
5587"123" が後ろに続かない数字以外の列を探したいと考えてみてください。
5588あなたは次のように書くかもしれません。
5589
5590 $_ = "ABC123";
5591 if ( /^\D*(?!123)/ ) { # Wrong!
5592 print "Yup, no 123 in $_\n";
5593 }
5594
5595=begin original
5596
5597But that isn't going to match; at least, not the way you're hoping. It
5598claims that there is no 123 in the string. Here's a clearer picture of
5599why that pattern matches, contrary to popular expectations:
5600
5601=end original
5602
5603ですがこれはマッチングしません; 少なくともなってほしかったようには。
5604これは文字列の中に 123 がないことを要求します。
5605よくある予想と比較してなぜパターンがマッチングするのかのわかりやすい
5606説明を次に示します:
5607
5608 $x = 'ABC123';
5609 $y = 'ABC445';
5610
5611 print "1: got $1\n" if $x =~ /^(ABC)(?!123)/;
5612 print "2: got $1\n" if $y =~ /^(ABC)(?!123)/;
5613
5614 print "3: got $1\n" if $x =~ /^(\D*)(?!123)/;
5615 print "4: got $1\n" if $y =~ /^(\D*)(?!123)/;
5616
5617=begin original
5618
5619This prints
5620
5621=end original
5622
5623これは次の出力となります
5624
5625 2: got ABC
5626 3: got AB
5627 4: got ABC
5628
5629=begin original
5630
5631You might have expected test 3 to fail because it seems to a more
5632general purpose version of test 1. The important difference between
5633them is that test 3 contains a quantifier (C<\D*>) and so can use
5634backtracking, whereas test 1 will not. What's happening is
5635that you've asked "Is it true that at the start of C<$x>, following 0 or more
5636non-digits, you have something that's not 123?" If the pattern matcher had
5637let C<\D*> expand to "ABC", this would have caused the whole pattern to
5638fail.
5639
5640=end original
5641
5642テスト 3 はテスト 1 のより一般的なバージョンなのでそれが失敗すると
5643考えたかもしれません。
5644この 2 つの重要な違いは、テスト 3 には量指定子(C<\D*>)が含まれているので
5645テスト1ではできなかったバックトラッキングを行うことが
5646できるところにあります。
5647ここであなたは「C<$x> のはじめで 0 個以上の非数字があるから 123 ではない
5648何かを得られるんじゃないの?」と聞くでしょう。
5649このパターンマッチングが C<\D*> を "ABC" に展開させると
5650これはパターン全体を失敗させることになります。
5651
5652=begin original
5653
5654The search engine will initially match C<\D*> with "ABC". Then it will
5655try to match C<(?!123)> with "123", which fails. But because
5656a quantifier (C<\D*>) has been used in the regular expression, the
5657search engine can backtrack and retry the match differently
5658in the hope of matching the complete regular expression.
5659
5660=end original
5661
5662探索エンジンは最初に C<\D*> を "ABC" にマッチングさせます。
5663そして C<(?!123)> を "123" にマッチングさせ、これは失敗します。
5664けれども量指定子 (C<\D*>) が正規表現の中で使われているので、探索エンジンは
5665バックトラックしてこの正規表現全体をマッチングさせるように異なるマッチングを
5666行うことができます。
5667
5668=begin original
5669
5670The pattern really, I<really> wants to succeed, so it uses the
5671standard pattern back-off-and-retry and lets C<\D*> expand to just "AB" this
5672time. Now there's indeed something following "AB" that is not
5673"123". It's "C123", which suffices.
5674
5675=end original
5676
5677このパターンは本当に、I<本当に> 成功したいので、これは標準的なパターンの
5678後退再試行を行い、この時に C<\D*> を "AB" のみに展開させます。
5679そして確かに "AB" の後ろは "123" ではありません。
5680"C123" は十分満たしています。
5681
5682=begin original
5683
5684We can deal with this by using both an assertion and a negation.
5685We'll say that the first part in C<$1> must be followed both by a digit
5686and by something that's not "123". Remember that the lookaheads
5687are zero-width expressions--they only look, but don't consume any
5688of the string in their match. So rewriting this way produces what
5689you'd expect; that is, case 5 will fail, but case 6 succeeds:
5690
5691=end original
5692
5693これは言明と否定の両方を使うことで処理することができます。
5694C<$1> の最初の部分は数字が続きかつそれは "123" ではないことを宣言します。
5695先読みはゼロ幅の式なのでそれがマッチングした文字列を全く消費しないことを
5696思い出してください。
5697そしてこれを必要なものを生成するように書き換えます;
5698つまり、5 のケースでは失敗し、6 のケースは成功します:
5699
5700 print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/;
5701 print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/;
5702
5703 6: got ABC
5704
5705=begin original
5706
5707In other words, the two zero-width assertions next to each other work as though
5708they're ANDed together, just as you'd use any built-in assertions: C</^$/>
5709matches only if you're at the beginning of the line AND the end of the
5710line simultaneously. The deeper underlying truth is that juxtaposition in
5711regular expressions always means AND, except when you write an explicit OR
5712using the vertical bar. C</ab/> means match "a" AND (then) match "b",
5713although the attempted matches are made at different positions because "a"
5714is not a zero-width assertion, but a one-width assertion.
5715
5716=end original
5717
5718言い換えると、このそれぞれの次にある2つのゼロ幅の言明はちょうど何か組み込みの
5719言明を使ったかのようにそれらがともに AND されているかのように動作します:
5720C</^$/> は行の始まりで且つ同時に行の終了でる時にのみマッチングします。
5721もっと深部での真実は、併記された正規表現は垂直線を使って明示的に OR を
5722書いたとき以外は常に AND を意味します。
5723C</ab/> は、"a" がゼロ幅の言明ではなく 1 文字幅の言明なので異なる場所で
5724マッチングが行われはしますが、 "a" にマッチング且つ(そして) "b" に
5725マッチングということを意味します。
5726
5727=begin original
5728
5729B<WARNING>: Particularly complicated regular expressions can take
5730exponential time to solve because of the immense number of possible
5731ways they can use backtracking to try for a match. For example, without
5732internal optimizations done by the regular expression engine, this will
5733take a painfully long time to run:
5734
5735=end original
5736
5737B<警告>: 特にコンパイルされた正規表現はマッチングのために
5738できる限りのバックトラックを非常に多くの回数行うので
5739解くために指数的な時間を必要とすることがあります。
5740例えば、正規表現エンジンの内部で行われる最適化がなかったときには、次の評価は
5741尋常じゃないくらい長時間かかります:
5742
5743 'aaaaaaaaaaaa' =~ /((a{0,5}){0,5})*[c]/
5744
5745=begin original
5746
5747And if you used C<"*">'s in the internal groups instead of limiting them
5748to 0 through 5 matches, then it would take forever--or until you ran
5749out of stack space. Moreover, these internal optimizations are not
5750always applicable. For example, if you put C<{0,5}> instead of C<"*">
5751on the external group, no current optimization is applicable, and the
5752match takes a long time to finish.
5753
5754=end original
5755
5756そしてもし内側のグループで 0 から 5 回にマッチングを制限する代わりに
5757C<"*"> を使うと、永久に、またはスタックを使い果たすまで
5758実行し続けることになります。
5759その上、これらの最適化は常にできるわけではありません。
5760例えば、外側のグループで C<"*"> の代わりに C<{0,5}> を使ったときに、現在の
5761最適化は適用されません; そしてマッチングが終わるまでの長い時間が
5762必要になります。
5763
5764=begin original
5765
5766A powerful tool for optimizing such beasts is what is known as an
5767"independent group",
5768which does not backtrack (see L</C<< (?>pattern) >>>). Note also that
5769zero-length lookahead/lookbehind assertions will not backtrack to make
5770the tail match, since they are in "logical" context: only
5771whether they match is considered relevant. For an example
5772where side-effects of lookahead I<might> have influenced the
5773following match, see L</C<< (?>pattern) >>>.
5774
5775=end original
5776
5777そのような野獣のような最適化のためのパワフルなツールとして
5778知られているものに、「独立グループ」があります; これはバックトラックを
5779行いません (L</C<< (?>pattern) >>> を参照)。
5780ゼロ幅の先読み/後読みの言明も「論理的な」文脈なので末尾のマッチングを
5781バックトラックしません: マッチングが関連して考慮されるかどうかだけです。
5782先読みの言明の副作用がそれに続くマッチングに影響する I<かもしれない> 例は、
5783L</C<< (?>pattern) >>> を参照してください。
5784
5785=head2 Script Runs
5786X<(*script_run:...)> X<(sr:...)>
5787X<(*atomic_script_run:...)> X<(asr:...)>
5788
5789(用字連続)
5790
5791=begin original
5792
5793A script run is basically a sequence of characters, all from the same
5794Unicode script (see L<perlunicode/Scripts>), such as Latin or Greek. In
5795most places a single word would never be written in multiple scripts,
5796unless it is a spoofing attack. An infamous example, is
5797
5798=end original
5799
5800用字連続は基本的には、ラテン文字やギリシャ文字のような、
5801全て同じ Unicode 用字 (L<perlunicode/Scripts> 参照) からの文字の並びです。
5802ほとんどの場所では、なりすまし攻撃でない限り、一つの単語は決して複数の用字で
5803書かれることはありません。
5804悪名高い例は次のものです:
5805
5806 paypal.com
5807
5808=begin original
5809
5810Those letters could all be Latin (as in the example just above), or they
5811could be all Cyrillic (except for the dot), or they could be a mixture
5812of the two. In the case of an internet address the C<.com> would be in
5813Latin, And any Cyrillic ones would cause it to be a mixture, not a
5814script run. Someone clicking on such a link would not be directed to
5815the real Paypal website, but an attacker would craft a look-alike one to
5816attempt to gather sensitive information from the person.
5817
5818=end original
5819
5820これらの文字は全て (直前のように) ラテン文字かもしれませんし、
5821(ドットを除いて) 全てキリル文字かもしれませんし、二つの混合かも
5822しれません。
5823インターネットアドレスの場合、C<.com> はラテン文字で、
5824キリル文字は混合となり用字連続ではありません。
5825誰かがこのようなリンクをクリックすると、本当の Paypal ウェブサイトに
5826移動せず、攻撃者がその人から機微情報を集めようとするために
5827見た目が似たものを細工するかもしれません。
5828
5829=begin original
5830
5831Starting in Perl 5.28, it is now easy to detect strings that aren't
5832script runs. Simply enclose just about any pattern like either of
5833these:
5834
5835=end original
5836
5837Perl 5.28 から、用字連続でない文字列を簡単に検出できるようになりました。
5838単にパターンを次のどちらかのような形で囲みます:
5839
5840 (*script_run:pattern)
5841 (*sr:pattern)
5842
5843=begin original
5844
5845What happens is that after I<pattern> succeeds in matching, it is
5846subjected to the additional criterion that every character in it must be
5847from the same script (see exceptions below). If this isn't true,
5848backtracking occurs until something all in the same script is found that
5849matches, or all possibilities are exhausted. This can cause a lot of
5850backtracking, but generally, only malicious input will result in this,
5851though the slow down could cause a denial of service attack. If your
5852needs permit, it is best to make the pattern atomic. This is so likely
5853to be what you want, that instead of writing this:
5854
5855=end original
5856
5857I<pattern> がマッチングした後に次のことが起きます;
5858その中の全ての文字が同じ用字であるという追加の条件が課されます
5859(後述する例外参照)。
5860これが真でない場合、全て同じ用字でマッチングする何かが見つかるか、
5861全ての可能性がなくなるまで、バックトラッキングが発生します。
5862これは多くのバックトラッキングを引き起こしますが、一般的に、
5863悪意のある入力だけがこれを引き起こします;
5864しかし、この速度低下はサービス不能攻撃を引き起こすかもしれません。
5865事情が許すなら、パターンをアトミックに書くのが最善です。
5866これはおそらくあなたが求めているものなので、次のように書く代わりに:
5867
5868 (*script_run:(?>pattern))
5869
5870=begin original
5871
5872you can write either of these:
5873
5874=end original
5875
5876次のどちらかのように書けます:
5877
5878 (*atomic_script_run:pattern)
5879 (*asr:pattern)
5880
5881=begin original
5882
5883(See L</C<(?E<gt>pattern)>>.)
5884
5885=end original
5886
5887(L</C<(?E<gt>pattern)>> を参照してください。)
5888
5889=begin original
5890
5891In Taiwan, Japan, and Korea, it is common for text to have a mixture of
5892characters from their native scripts and base Chinese. Perl follows
5893Unicode's UTS 39 (L<http://unicode.org/reports/tr39/>) Unicode Security
5894Mechanisms in allowing such mixtures.
5895
5896=end original
5897
5898台湾、日本、韓国では、独自の用字からの文字と中国語を基にした文字が
5899混合している文章は一般的です。
5900Perl はこのような混合を許すために Unicode の UTS 39
5901(L<http://unicode.org/reports/tr39/>) Unicode Security Mechanisms に
5902従います。
5903
5904=begin original
5905
5906The rules used for matching decimal digits are somewhat different. Many
5907scripts have their own sets of digits equivalent to the Western C<0>
5908through C<9> ones. A few, such as Arabic, have more than one set. For
5909a string to be considered a script run, all digits in it must come from
5910the same set, as determined by the first digit encountered. The ASCII
5911C<[0-9]> are accepted as being in any script, even those that have their
5912own set. This is because these are often used in commerce even in such
5913scripts. But any mixing of the ASCII and other digits will cause the
5914sequence to not be a script run, failing the match. As an example,
5915
5916=end original
5917
591810 進数字とマッチングするために使われる規則は少し異なります。
5919多くの用字は、西洋の C<0> から C<9> と等価な独自の数字の集合を持ちます。
5920アラビア文字のように、複数の集合を持つものもあります。
5921用字連続が考慮される文字列については、全ての数字は、遭遇した
5922最初の数字で決定されるものと同じ集合でなければなりません。
5923たとえ独自の集合を持っている用字でも ASCII の C<[0-9]> は受け入れられます。
5924これは、これらがそのような用字でも照合の分野ではしばしば使われるからです。
5925しかし ASCII とその他の数字の混合は、用字連続とはならず、
5926マッチングに失敗します。
5927例えば:
5928
5929 qr/(*script_run: \d+ \b )/x
5930
5931=begin original
5932
5933guarantees that the digits matched will all be from the same set of 10.
5934You won't get a look-alike digit from a different script that has a
5935different value than what it appears to be.
5936
5937=end original
5938
5939これはマッチングした数字が全て同じ集合の 10 文字からであることを保証します。
5940見た目と異なる値を持つ、異なる用字からの数字に見えるものを得ることは
5941ありません。
5942
5943=begin original
5944
5945Unicode has three pseudo scripts that are handled specially.
5946
5947=end original
5948
5949Unicode には特別に扱われる三つの疑似用字があります。
5950
5951=begin original
5952
5953"Unknown" is applied to code points whose meaning has yet to be
5954determined. Perl currently will match as a script run, any single
5955character string consisting of one of these code points. But any string
5956longer than one code point containing one of these will not be
5957considered a script run.
5958
5959=end original
5960
5961"Unknown" は、意味がまだ決定されていない符号位置に適用されます。
5962Perl は現在の所それらのうちの一つの符号位置からなる 1 文字文字列を
5963用字連続としてマッチングします。
5964しかし、それらの一つを含む 2 符号位置以上の文字列は用字連続として
5965扱われません。
5966
5967=begin original
5968
5969"Inherited" is applied to characters that modify another, such as an
5970accent of some type. These are considered to be in the script of the
5971master character, and so never cause a script run to not match.
5972
5973=end original
5974
5975"Inherited" は、一部のアクセントのように、他のものを変更する文字に
5976適用されます。
5977これらは元の文字の用字として扱われるので、
5978マッチングしない用字連続になることはありません。
5979
5980=begin original
5981
5982The other one is "Common". This consists of mostly punctuation, emoji,
5983and characters used in mathematics and music, and the ASCII digits C<0>
5984through C<9>. These characters can appear intermixed in text in many of
5985the world's scripts. These also don't cause a script run to not match,
5986except any ASCII digits encountered have to obey the decimal digit rules
5987described above.
5988
5989=end original
5990
5991もう一つは "Common" です。
5992これはほとんど句読点、絵文字、数学と音楽で使われる文字、および
5993ASCII の数字 C<0> から C<9> で構成されます。
5994これらの文字は世界中の多くの用字の文章で混ぜられて現れます。
5995これらもまた、マッチングしない用字連続にはなりません;
5996ただし、現れた ASCII の数字は、前述した 10 進数の規則に従う必要があります。
5997
5998=begin original
5999
6000This construct is non-capturing. You can add parentheses to I<pattern>
6001to capture, if desired. You will have to do this if you plan to use
6002L</(*ACCEPT) (*ACCEPT:arg)> and not have it bypass the script run
6003checking.
6004
6005=end original
6006
6007この構文は捕捉しません。
6008捕捉したい場合は、その I<pattern> にかっこを追加できます。
6009L</(*ACCEPT) (*ACCEPT:arg)> を使う予定で、用字連続チェックを
6010迂回しない場合は、こうすることが必要でしょう。
6011
6012=begin original
6013
6014This feature is experimental, and the exact syntax and details of
6015operation are subject to change; using it yields a warning in the
6016C<experimental::script_run> category.
6017
6018=end original
6019
6020この機能は実験的で、正確な文法と操作の詳細は変更される予定です;
6021これを使うと、C<experimental::script_run> カテゴリの警告が出力されます。
6022
6023=begin original
6024
6025The C<Script_Extensions> property is used as the basis for this feature.
6026
6027=end original
6028
6029この機能の基礎としては C<Script_Extensions> 特性が使われます。
6030
6031=head2 Special Backtracking Control Verbs
6032
6033(特殊なバックトラック制御記号)
6034
6035=begin original
6036
6037These special patterns are generally of the form C<(*I<VERB>:I<ARG>)>. Unless
6038otherwise stated the I<ARG> argument is optional; in some cases, it is
6039mandatory.
6040
6041=end original
6042
6043これらの特殊なパターンは C<(*I<VERB>:I<ARG>)> という一般形式を持っています。
6044特に記されていない限り、I<ARG> はオプションです; 一部の場合では、
6045これは必須です。
6046
6047=begin original
6048
40666049Any pattern containing a special backtracking verb that allows an argument
40676050has the special behaviour that when executed it sets the current package's
40686051C<$REGERROR> and C<$REGMARK> variables. When doing so the following
40696052rules apply:
40706053
40716054=end original
40726055
40736056引数を許可する特殊バックトラック制御記号を含んでいる全てのパターンは、
40746057それが実行されると現在のパッケージの C<$REGERROR> 及び C<$REGMARK> 変数を
40756058設定する特殊な振る舞いを持っています。
40766059これが行われる時以下の手順が適用されます。
40776060
40786061=begin original
40796062
4080On failure, the C<$REGERROR> variable will be set to the ARG value of the
6063On failure, the C<$REGERROR> variable will be set to the I<ARG> value of the
40816064verb pattern, if the verb was involved in the failure of the match. If the
4082ARG part of the pattern was omitted, then C<$REGERROR> will be set to the
6065I<ARG> part of the pattern was omitted, then C<$REGERROR> will be set to the
40836066name of the last C<(*MARK:NAME)> pattern executed, or to TRUE if there was
40846067none. Also, the C<$REGMARK> variable will be set to FALSE.
40856068
40866069=end original
40876070
40886071失敗時には C<$REGERROR> 変数には、記号がマッチングの失敗の中で
4089使われていたのならその記号パターンの ARG の値がセットされます。
6072使われていたのならその記号パターンの I<ARG> の値がセットされます。
4090もしパターンの ARG 部分が省略されていたときには、C<$REGERROR> には
6073もしパターンの I<ARG> 部分が省略されていたときには、C<$REGERROR> には
40916074最後に実行された C<(*MARK:NAME)> パターンの名前、またはそれもなければ
40926075真に設定されます。
40936076また、C<$REGMARK> 変数は偽に設定されます。
40946077
40956078=begin original
40966079
40976080On a successful match, the C<$REGERROR> variable will be set to FALSE, and
40986081the C<$REGMARK> variable will be set to the name of the last
40996082C<(*MARK:NAME)> pattern executed. See the explanation for the
41006083C<(*MARK:NAME)> verb below for more details.
41016084
41026085=end original
41036086
41046087マッチングの成功時には、C<$REGERROR> 変数は偽に設定され、C<$REGMARK> 変数には
41056088最後に実行された C<(*MARK:NAME)> パターンの名前が設定されます。
41066089詳細は C<(*MARK:NAME)> 記号の説明を参照してください。
41076090
41086091=begin original
41096092
41106093B<NOTE:> C<$REGERROR> and C<$REGMARK> are not magic variables like C<$1>
41116094and most other regex-related variables. They are not local to a scope, nor
41126095readonly, but instead are volatile package variables similar to C<$AUTOLOAD>.
4113Use C<local> to localize changes to them to a specific scope if necessary.
6096They are set in the package containing the code that I<executed> the regex
6097(rather than the one that compiled it, where those differ). If necessary, you
6098can use C<local> to localize changes to these variables to a specific scope
6099before executing a regex.
41146100
41156101=end original
41166102
41176103B<補足:> C<$REGERROR> 及び C<$REGMARK> は C<$1> や他の多くの
41186104正規表現関連の変数のようにマジック変数ではありません。
41196105それらはスコープ内にローカルにならず、読み込み専用でもありませんが、
41206106C<$AUTOLOAD> と似た揮発するパッケージ変数です。
4121必要時特定のスコープ内に変更を留めたいときにC<local> を使ってくだい。
6107これらには正規表現が I<実行される> コード含むパッケージが設定れます
6108(コンパイルされるコードではありません; これは異なることがあります)。
6109必要な場合は、正規表現を実行する前に
6110これらの変数の変更を特定のスコープ内に留めるために C<local> を使えます。
41226111
41236112=begin original
41246113
41256114If a pattern does not contain a special backtracking verb that allows an
41266115argument, then C<$REGERROR> and C<$REGMARK> are not touched at all.
41276116
41286117=end original
41296118
41306119もしパターンが引数を許可する特殊バックトラック記号を含んでなかった場合には、
41316120C<$REGERROR> 及び C<$REGMARK> は全く触られません。
41326121
41336122=over 3
41346123
4135=item Verbs that take an argument
6124=item Verbs
41366125
4137(引数を取る動詞)
6126(動詞)
41386127
41396128=over 4
41406129
41416130=item C<(*PRUNE)> C<(*PRUNE:NAME)>
41426131X<(*PRUNE)> X<(*PRUNE:NAME)>
41436132
41446133=begin original
41456134
41466135This zero-width pattern prunes the backtracking tree at the current point
4147when backtracked into on failure. Consider the pattern C<A (*PRUNE) B>,
6136when backtracked into on failure. Consider the pattern C</I<A> (*PRUNE) I<B>/>,
4148where A and B are complex patterns. Until the C<(*PRUNE)> verb is reached,
6137where I<A> and I<B> are complex patterns. Until the C<(*PRUNE)> verb is reached,
4149A may backtrack as necessary to match. Once it is reached, matching
6138I<A> may backtrack as necessary to match. Once it is reached, matching
4150continues in B, which may also backtrack as necessary; however, should B
6139continues in I<B>, which may also backtrack as necessary; however, should B
41516140not match, then no further backtracking will take place, and the pattern
41526141will fail outright at the current starting position.
41536142
41546143=end original
41556144
41566145このゼロ幅のパターンは失敗でバックトラックしてきたときに現在の位置で
41576146バックトラックツリーを刈り取ります。
4158C<A (*PRUNE) B> というパターンで A も B も複雑なパターンである時を
6147C</I<A> (*PRUNE) I<B>/> というパターンで I<A>I<B> も複雑なパターンである時を
41596148考えてみます。
4160C<(*PRUNE)> に達するまでは、A はマッチングに必要であれば
6149C<(*PRUNE)> に達するまでは、I<A> はマッチングに必要であれば
41616150バックトラックしていきます。
4162しかし一旦そこに達して B に続くと、そこでも必要に応じてバックトラックします;
6151しかし一旦そこに達して I<B> に続くと、そこでも必要に応じてバックトラックします;
41636152しかしながら、B がマッチングしなかったときにはそれ以上のバックトラックは
41646153行われず、現在の開始位置でのマッチングはすぐに失敗します。
41656154
41666155=begin original
41676156
41686157The following example counts all the possible matching strings in a
41696158pattern (without actually matching any of them).
41706159
41716160=end original
41726161
41736162次の例ではパターンに対してマッチングできるすべての文字列を(実際には
41746163マッチングさせずに)数えます。
41756164
41766165 'aaab' =~ /a+b?(?{print "$&\n"; $count++})(*FAIL)/;
41776166 print "Count=$count\n";
41786167
41796168=begin original
41806169
41816170which produces:
41826171
41836172=end original
41846173
41856174この出力:
41866175
41876176 aaab
41886177 aaa
41896178 aa
41906179 a
41916180 aab
41926181 aa
41936182 a
41946183 ab
41956184 a
41966185 Count=9
41976186
41986187=begin original
41996188
42006189If we add a C<(*PRUNE)> before the count like the following
42016190
42026191=end original
42036192
42046193次のように数える前に C<(*PRUNE)> を加えると
42056194
42066195 'aaab' =~ /a+b?(*PRUNE)(?{print "$&\n"; $count++})(*FAIL)/;
42076196 print "Count=$count\n";
42086197
42096198=begin original
42106199
42116200we prevent backtracking and find the count of the longest matching string
42126201at each matching starting point like so:
42136202
42146203=end original
42156204
42166205バックトラックを妨げ次のように各開始位置での一番長いマッチング文字列を
42176206数えるようになります:
42186207
42196208 aaab
42206209 aab
42216210 ab
42226211 Count=3
42236212
42246213=begin original
42256214
42266215Any number of C<(*PRUNE)> assertions may be used in a pattern.
42276216
42286217=end original
42296218
423062191つのパターン内で C<(*PRUNE)> 言明はいくつでも使えます。
42316220
42326221=begin original
42336222
4234See also C<< (?>pattern) >> and possessive quantifiers for other ways to
6223See also C<<< L<< /(?>pattern) >> >>> and possessive quantifiers for
6224other ways to
42356225control backtracking. In some cases, the use of C<(*PRUNE)> can be
42366226replaced with a C<< (?>pattern) >> with no functional difference; however,
42376227C<(*PRUNE)> can be used to handle cases that cannot be expressed using a
42386228C<< (?>pattern) >> alone.
42396229
42406230=end original
42416231
4242バックトラックを制御する他の方法として C<< (?>pattern) >>
6232バックトラックを制御する他の方法として C<<< L<< /(?>pattern) >> >>>
42436233及び絶対最大量指定子も参照してください。
42446234幾つかのケースにおいては C<(*PRUNE)> の利用は機能的な違いなしに
42456235C<< (?>pattern) >> で置き換えることができます; しかしながら C<(*PRUNE)> は
42466236C<< (?>pattern) >> 単独では表現できないケースを扱うために使えます。
42476237
42486238=item C<(*SKIP)> C<(*SKIP:NAME)>
42496239X<(*SKIP)>
42506240
42516241=begin original
42526242
42536243This zero-width pattern is similar to C<(*PRUNE)>, except that on
42546244failure it also signifies that whatever text that was matched leading up
42556245to the C<(*SKIP)> pattern being executed cannot be part of I<any> match
42566246of this pattern. This effectively means that the regex engine "skips" forward
42576247to this position on failure and tries to match again, (assuming that
42586248there is sufficient room to match).
42596249
42606250=end original
42616251
42626252このゼロ幅のパターンは C<*PRUNE> と似ていますが、実行されている
42636253C<(*SKIP)> パターンまでにマッチングしたテキストはこのパターンの
42646254I<どの>マッチングの一部にもならないことを示します。
42656255これは正規表現エンジンがこの位置まで失敗として「スキップ」して(マッチングに
42666256十分な空間があれば)再びマッチングを試みることを効率的に意味します。
42676257
42686258=begin original
42696259
42706260The name of the C<(*SKIP:NAME)> pattern has special significance. If a
42716261C<(*MARK:NAME)> was encountered while matching, then it is that position
42726262which is used as the "skip point". If no C<(*MARK)> of that name was
42736263encountered, then the C<(*SKIP)> operator has no effect. When used
42746264without a name the "skip point" is where the match point was when
4275executing the (*SKIP) pattern.
6265executing the C<(*SKIP)> pattern.
42766266
42776267=end original
42786268
42796269C<(*SKIP:NAME)> パターンの名前部分には特別な意味があります。
42806270もしマッチングにおいて C<(*MARK:NAME)> に遭遇すると、それは「スキップ
42816271位置」として使われる位置になります。
42826272その名前の C<(*MARK)> と東宮していなければ、C<(*SKIP)> 操作は効果を
42836273持ちません。
4284名前がなければ「スキップ位置」は(*SKIP)パターンの実行されたときに
6274名前がなければ「スキップ位置」は C<(*SKIP)> パターンの実行されたときに
42856275マッチングポイントが使われます。
42866276
42876277=begin original
42886278
42896279Compare the following to the examples in C<(*PRUNE)>; note the string
42906280is twice as long:
42916281
42926282=end original
42936283
42946284以下の例を C<(*PRUNE)> と比べてみてください;
42956285文字列が2倍になってることに注意してください:
42966286
42976287 'aaabaaab' =~ /a+b?(*SKIP)(?{print "$&\n"; $count++})(*FAIL)/;
42986288 print "Count=$count\n";
42996289
43006290=begin original
43016291
43026292outputs
43036293
43046294=end original
43056295
43066296これの出力は
43076297
43086298 aaab
43096299 aaab
43106300 Count=2
43116301
43126302=begin original
43136303
43146304Once the 'aaab' at the start of the string has matched, and the C<(*SKIP)>
43156305executed, the next starting point will be where the cursor was when the
43166306C<(*SKIP)> was executed.
43176307
43186308=end original
43196309
43206310いったん文字列の最初の 'aaab' がマッチングして、C<(*SKIP)> が実行されると、
43216311次の開始位置は C<(*SKIP)> が実行されたときのカーソルがいた位置になります。
43226312
43236313=item C<(*MARK:NAME)> C<(*:NAME)>
43246314X<(*MARK)> X<(*MARK:NAME)> X<(*:NAME)>
43256315
43266316=begin original
43276317
43286318This zero-width pattern can be used to mark the point reached in a string
43296319when a certain part of the pattern has been successfully matched. This
43306320mark may be given a name. A later C<(*SKIP)> pattern will then skip
43316321forward to that point if backtracked into on failure. Any number of
4332C<(*MARK)> patterns are allowed, and the NAME portion may be duplicated.
6322C<(*MARK)> patterns are allowed, and the I<NAME> portion may be duplicated.
43336323
43346324=end original
43356325
43366326このゼロ幅のマッチングはパターン内の特定の箇所がマッチングに成功したときに、
43376327文字列の中で達した位置を記録するために使われます。
43386328このマークには名前をつけることもできます。
43396329後者の C<(*SKIP)> パターンは失敗時でバックトラックしたときにその箇所まで
43406330スキップします。
4341C<(*MARK)> パターンはいくつでも使うことができて、NAME 部分は
6331C<(*MARK)> パターンはいくつでも使うことができて、I<NAME> 部分は
43426332重複することもあります。
43436333
43446334=begin original
43456335
43466336In addition to interacting with the C<(*SKIP)> pattern, C<(*MARK:NAME)>
43476337can be used to "label" a pattern branch, so that after matching, the
43486338program can determine which branches of the pattern were involved in the
43496339match.
43506340
43516341=end original
43526342
43536343C<(*SKIP)> パターンとの相互動作に加えて、C<(*MARK:NAME)> はパターン分岐の
43546344「ラベル」としても使うことができます; このためマッチングの後で、プログラムは
43556345そのマッチングにおいてパターンのどの分岐が使われたのかを知ることができます。
43566346
43576347=begin original
43586348
43596349When a match is successful, the C<$REGMARK> variable will be set to the
43606350name of the most recently executed C<(*MARK:NAME)> that was involved
43616351in the match.
43626352
43636353=end original
43646354
43656355マッチングの成功時に、C<$REGMARK> 変数はマッチングの中で一番最近に
43666356実行された C<(*MARK:NAME)> の名前を設定します。
43676357
43686358=begin original
43696359
43706360This can be used to determine which branch of a pattern was matched
43716361without using a separate capture group for each branch, which in turn
43726362can result in a performance improvement, as perl cannot optimize
43736363C</(?:(x)|(y)|(z))/> as efficiently as something like
43746364C</(?:x(*MARK:x)|y(*MARK:y)|z(*MARK:z))/>.
43756365
43766366=end original
43776367
43786368これは書く分岐で別々の捕捉グループを使うことなしにパターンのどの分岐が
43796369マッチングしたのかを知るために使うことができます; これは perl は
43806370C</(?:(x)|(y)|(z))/> を C</(?:x(*MARK:x)|y(*MARK:y)|z(*MARK:z))/> 程度に
43816371効率的には最適化できないためパフォーマンスの向上をもたらします。
43826372
43836373=begin original
43846374
43856375When a match has failed, and unless another verb has been involved in
43866376failing the match and has provided its own name to use, the C<$REGERROR>
43876377variable will be set to the name of the most recently executed
43886378C<(*MARK:NAME)>.
43896379
43906380=end original
43916381
43926382マッチングが失敗して、そして他の記号がマッチングの失敗で行われずかつ名前を
43936383持っているというのでなければ、C<$REGERROR> 変数には一番最近に実行された
43946384名前が設定されます。
43956385
43966386=begin original
43976387
43986388See L</(*SKIP)> for more details.
43996389
44006390=end original
44016391
44026392詳細は L</(*SKIP)> を参照してください。
44036393
44046394=begin original
44056395
44066396As a shortcut C<(*MARK:NAME)> can be written C<(*:NAME)>.
44076397
44086398=end original
44096399
44106400C<(*MARK:NAME)> の短縮形として C<(*:NAME)> とも記述できます。
44116401
44126402=item C<(*THEN)> C<(*THEN:NAME)>
44136403
44146404=begin original
44156405
44166406This is similar to the "cut group" operator C<::> from Perl 6. Like
44176407C<(*PRUNE)>, this verb always matches, and when backtracked into on
44186408failure, it causes the regex engine to try the next alternation in the
44196409innermost enclosing group (capturing or otherwise) that has alternations.
44206410The two branches of a C<(?(condition)yes-pattern|no-pattern)> do not
44216411count as an alternation, as far as C<(*THEN)> is concerned.
44226412
44236413=end original
44246414
44256415これは Perl 6 の "cut group" 演算子 C<::> と似ています。
44266416C<(*PRUNE)> のように、この記号は常にマッチングし、そして失敗で
44276417バックトラックした時に正規表現エンジンに、代替のある一番内側で閉じている
44286418グループ(キャプチャでもそうでなくとも)で次の代替を試みるようにさせます。
44296419C<(*THEN)> が有効である限り、
44306420C<(?(condition)yes-pattern|no-pattern)> の二つの枝は代替とは扱われません。
44316421
44326422=begin original
44336423
44346424Its name comes from the observation that this operation combined with the
4435alternation operator (C<|>) can be used to create what is essentially a
6425alternation operator (C<"|">) can be used to create what is essentially a
44366426pattern-based if/then/else block:
44376427
44386428=end original
44396429
4440この名前は代替演算子(C<|>) と連結されたこの演算子で本質的にパターンベースの
6430この名前は代替演算子 (C<"|">) と連結されたこの演算子で本質的にパターンベースの
44416431if/then/else ブロックとなるものを作るために使うことが
44426432できることからきています:
44436433
44446434 ( COND (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ )
44456435
44466436=begin original
44476437
44486438Note that if this operator is used and NOT inside of an alternation then
44496439it acts exactly like the C<(*PRUNE)> operator.
44506440
44516441=end original
44526442
44536443この演算子が使われていてそしてそれが代替の内側ではなければ
44546444これはちょうど C<(*PRUNE)> 演算子のように動作します。
44556445
44566446 / A (*PRUNE) B /
44576447
44586448=begin original
44596449
44606450is the same as
44616451
44626452=end original
44636453
44646454は次と同じです
44656455
44666456 / A (*THEN) B /
44676457
44686458=begin original
44696459
44706460but
44716461
44726462=end original
44736463
44746464しかし
44756465
4476 / ( A (*THEN) B | C (*THEN) D ) /
6466 / ( A (*THEN) B | C ) /
44776467
44786468=begin original
44796469
44806470is not the same as
44816471
44826472=end original
44836473
44846474は次と同じではありません
44856475
4486 / ( A (*PRUNE) B | C (*PRUNE) D ) /
6476 / ( A (*PRUNE) B | C ) /
44876477
44886478=begin original
44896479
4490as after matching the A but failing on the B the C<(*THEN)> verb will
6480as after matching the I<A> but failing on the I<B> the C<(*THEN)> verb will
4491backtrack and try C; but the C<(*PRUNE)> verb will simply fail.
6481backtrack and try I<C>; but the C<(*PRUNE)> verb will simply fail.
44926482
44936483=end original
44946484
4495A にマッチングしたけれど B に失敗した後 C<(*THEN)> 記号はバックトラックして
6485I<A> にマッチングしたけれど I<B> に失敗した後 C<(*THEN)> 記号は
4496C を試みます; しかし C<(*PRUNE)> 記号であれば単純に失敗します。
6486バックトラックして I<C> を試みます; しかし C<(*PRUNE)> 記号であれば
6487単純に失敗します。
44976488
4498=back
6489=item C<(*COMMIT)> C<(*COMMIT:args)>
4499
4500=item Verbs without an argument
4501
4502=over 4
4503
4504=item C<(*COMMIT)>
45056490X<(*COMMIT)>
45066491
45076492=begin original
45086493
45096494This is the Perl 6 "commit pattern" C<< <commit> >> or C<:::>. It's a
45106495zero-width pattern similar to C<(*SKIP)>, except that when backtracked
45116496into on failure it causes the match to fail outright. No further attempts
45126497to find a valid match by advancing the start pointer will occur again.
45136498For example,
45146499
45156500=end original
45166501
45176502これは Perl 6 の"コミットパターン" C<< <commit> >> または C<:::> です。
45186503これは C<(*SKIP)> と似たゼロ幅のパターンですが、失敗でバックトラックした
45196504際にマッチングがすぐに失敗する点で異なります。
45206505それ以降で開始位置を進めて有効なマッチングを探す試行は行われません。
45216506例えば、
45226507
45236508 'aaabaaab' =~ /a+b?(*COMMIT)(?{print "$&\n"; $count++})(*FAIL)/;
45246509 print "Count=$count\n";
45256510
45266511=begin original
45276512
45286513outputs
45296514
45306515=end original
45316516
45326517これの出力は
45336518
45346519 aaab
45356520 Count=1
45366521
45376522=begin original
45386523
45396524In other words, once the C<(*COMMIT)> has been entered, and if the pattern
45406525does not match, the regex engine will not try any further matching on the
45416526rest of the string.
45426527
45436528=end original
45446529
45456530言い換えると、いったん C<(*COMMIT)> に入った後に、そのパターンが
45466531マッチングしなかったのなら、正規表現エンジンは文字列の残りに対して
45476532それ以上のマッチングを試みません。
45486533
4549=item C<(*FAIL)> C<(*F)>
6534=item C<(*FAIL)> C<(*F)> C<(*FAIL:arg)>
45506535X<(*FAIL)> X<(*F)>
45516536
45526537=begin original
45536538
45546539This pattern matches nothing and always fails. It can be used to force the
45556540engine to backtrack. It is equivalent to C<(?!)>, but easier to read. In
4556fact, C<(?!)> gets optimised into C<(*FAIL)> internally.
6541fact, C<(?!)> gets optimised into C<(*FAIL)> internally. You can provide
6542an argument so that if the match fails because of this C<FAIL> directive
6543the argument can be obtained from C<$REGERROR>.
45576544
45586545=end original
45596546
45606547このパターンは何にもマッチングせず常に失敗します。
45616548これはエンジンを強制的にバックトラックさせるために使えます。
45626549これは C<(?!)> と等価ですが、より読みやすくなっています。
45636550実際、C<(?!)> は内部的には C<(*FAIL)> に最適化されます。
6551この C<FAIL> 指示子によってマッチングが失敗したときに
6552C<$REGERROR> から得られる、引数を指定できます。
45646553
45656554=begin original
45666555
45676556It is probably useful only when combined with C<(?{})> or C<(??{})>.
45686557
45696558=end original
45706559
45716560これはおそらく C<(?{})> または C<(??{})> と組み合わせた時にだけ
45726561役に立つでしょう。
45736562
4574=item C<(*ACCEPT)>
6563=item C<(*ACCEPT)> C<(*ACCEPT:arg)>
45756564X<(*ACCEPT)>
45766565
45776566=begin original
45786567
4579B<WARNING:> This feature is highly experimental. It is not recommended
4580for production code.
4581
4582=end original
4583
4584B<警告:> この機能は強く実験的です。
4585製品コードでは推奨されません。
4586
4587=begin original
4588
45896568This pattern matches nothing and causes the end of successful matching at
45906569the point at which the C<(*ACCEPT)> pattern was encountered, regardless of
45916570whether there is actually more to match in the string. When inside of a
45926571nested pattern, such as recursion, or in a subpattern dynamically generated
45936572via C<(??{})>, only the innermost pattern is ended immediately.
45946573
45956574=end original
45966575
45976576このパターンマッチングは何もせず C<(*ACCEPT)> パターンと遭遇した場所で
45986577文字列の中で実際にもっとマッチングするものがあるかどうかにかかわらず
45996578成功のマッチングを終了させます。
46006579再帰、または C<(??{})> といったネストしたパターンの内側では、一番内側の
46016580パターンのみがすぐに終了します。
46026581
46036582=begin original
46046583
46056584If the C<(*ACCEPT)> is inside of capturing groups then the groups are
46066585marked as ended at the point at which the C<(*ACCEPT)> was encountered.
46076586For instance:
46086587
46096588=end original
46106589
46116590C<(*ACCEPT)> が捕捉グループの内側で使われた場合捕捉グループは
46126591C<(*ACCEPT)> と遭遇した位置で終了とマークされます。
46136592例えば:
46146593
46156594 'AB' =~ /(A (A|B(*ACCEPT)|C) D)(E)/x;
46166595
46176596=begin original
46186597
4619will match, and C<$1> will be C<AB> and C<$2> will be C<B>, C<$3> will not
6598will match, and C<$1> will be C<AB> and C<$2> will be C<"B">, C<$3> will not
46206599be set. If another branch in the inner parentheses was matched, such as in the
4621string 'ACDE', then the C<D> and C<E> would have to be matched as well.
6600string 'ACDE', then the C<"D"> and C<"E"> would have to be matched as well.
46226601
46236602=end original
46246603
4625はマッチングし、C<$1> は C<AB> になり、C<$2> は C<B> に、そして
6604はマッチングし、C<$1> は C<AB> になり、C<$2> は C<"B"> に、そして
46266605C<$3> は設定されません。
4627'ACDE' のようにかっこの内側で他の分岐がマッチングしたのなら、C<D> 及び
6606'ACDE' のようにかっこの内側で他の分岐がマッチングしたのなら、
4628C<E> もマッチングします。
6607C<"D"> と C<"E"> もマッチングします。
46296608
4630=back
4631
4632=back
4633
4634=head2 Backtracking
4635X<backtrack> X<backtracking>
4636
4637(バックトラック)
4638
46396609=begin original
46406610
4641NOTE: This section presents an abstract approximation of regular
6611You can provide an argument, which will be available in the var
4642expression behavior. For a more rigorous (and complicated) view of
6612C<$REGMARK> after the match completes.
4643the rules involved in selecting a match among possible alternatives,
4644see L<Combining RE Pieces>.
46456613
46466614=end original
46476615
4648補足: このセクショでは正規表現の振る舞い関する抽象的概要
6616マッチグが成功した後 C<$REGMARK> 変数で利用可能引数指定できます。
4649説明します。
4650可能な代替におけるマッチングの選択におけるルールの厳密な(そして複雑な)
4651説明は L<Combining RE Pieces> を参照してください。
46526617
4653=begin original
6618=back
46546619
4655A fundamental feature of regular expression matching involves the
6620=back
4656notion called I<backtracking>, which is currently used (when needed)
4657by all regular non-possessive expression quantifiers, namely C<*>, C<*?>, C<+>,
4658C<+?>, C<{n,m}>, and C<{n,m}?>. Backtracking is often optimized
4659internally, but the general principle outlined here is valid.
46606621
4661=end original
6622=head2 Warning on C<\1> Instead of C<$1>
46626623
4663正規表現マッチングの基本的な機能には最近(必要あれば)すべての強欲で
6624(C<$1> く C<\1> だったときの警告)
4664正規表現量指定子、つまり、C<*>, C<*?>, C<+>, C<+?>, C<{n,m}>, C<{n,m}?> で
4665使われる I<バックトラッキング> と呼ばれる概念が含まれています。
4666バックトラックはしばしば内部で最適化されますが、ここで概説する一般的な
4667原則は妥当です。
46686625
46696626=begin original
46706627
4671For a regular expression to match, the I<entire> regular expression must
4672match, not just part of it. So if the beginning of a pattern containing a
4673quantifier succeeds in a way that causes later parts in the pattern to
4674fail, the matching engine backs up and recalculates the beginning
4675part--that's why it's called backtracking.
4676
4677=end original
4678
4679正規表現がマッチングする時、その正規表現の一部ではなく、
4680I<全体> がマッチングしなければなりません。
4681そのためもしパターンの前半にパターンの後半部分を失敗させてしまう
4682量指定子が含まれているのなら、マッチングングエンジンはいったん戻って
4683開始位置を再計算します -- これがバックトラッキングと呼ばれる所以です。
4684
4685=begin original
4686
4687Here is an example of backtracking: Let's say you want to find the
4688word following "foo" in the string "Food is on the foo table.":
4689
4690=end original
4691
4692バックトラッキングの例をあげてみます: "Food is on the foo table." という
4693文字列の中で "foo" に続く単語を取り出してください:
4694
4695 $_ = "Food is on the foo table.";
4696 if ( /\b(foo)\s+(\w+)/i ) {
4697 print "$2 follows $1.\n";
4698 }
4699
4700=begin original
4701
4702When the match runs, the first part of the regular expression (C<\b(foo)>)
4703finds a possible match right at the beginning of the string, and loads up
4704$1 with "Foo". However, as soon as the matching engine sees that there's
4705no whitespace following the "Foo" that it had saved in $1, it realizes its
4706mistake and starts over again one character after where it had the
4707tentative match. This time it goes all the way until the next occurrence
4708of "foo". The complete regular expression matches this time, and you get
4709the expected output of "table follows foo."
4710
4711=end original
4712
4713マッチングが実行される時、正規表現の最初の部分 (C<\b(foo)>) は開始文字列の
4714右側で可能なマッチングを探します; そして $1 に "Foo" をロードします。
4715しかし、すぐにマッチングエンジンは $1 に保存した "Foo" の後に空白が
4716無いことを見つけ、それが失敗だったことを検出して仮にマッチングさせた
4717場所の1文字後から開始します。
4718この時次の "foo" の出現まで進みます。
4719この時に正規表現は完全にマッチングし、予測した出力 "table follows foo." を
4720得ます。
4721
4722=begin original
4723
4724Sometimes minimal matching can help a lot. Imagine you'd like to match
4725everything between "foo" and "bar". Initially, you write something
4726like this:
4727
4728=end original
4729
4730最小マッチングが役立つこともあります。
4731"foo" と "bar" の間の全てにマッチングしたいと考えてください。
4732最初に、次のように書くかもしれません:
4733
4734 $_ = "The food is under the bar in the barn.";
4735 if ( /foo(.*)bar/ ) {
4736 print "got <$1>\n";
4737 }
4738
4739=begin original
4740
4741Which perhaps unexpectedly yields:
4742
4743=end original
4744
4745しかしこれは考えたのと違う結果となるでしょう:
4746
4747 got <d is under the bar in the >
4748
4749=begin original
4750
4751That's because C<.*> was greedy, so you get everything between the
4752I<first> "foo" and the I<last> "bar". Here it's more effective
4753to use minimal matching to make sure you get the text between a "foo"
4754and the first "bar" thereafter.
4755
4756=end original
4757
4758これは C<.*> が貪欲であり、そのために I<最初の> "foo" と I<最後の>
4759"bar" の間にある全てを取り出してしまいます。
4760次に "foo" とその後の最初の "bar" の間にあるテキストを取り出す
4761最小マッチングを使ったもっと効率的な方法を示します:
4762
4763 if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
4764 got <d is under the >
4765
4766=begin original
4767
4768Here's another example. Let's say you'd like to match a number at the end
4769of a string, and you also want to keep the preceding part of the match.
4770So you write this:
4771
4772=end original
4773
4774別の例も出してみます。
4775文字列の最後にある数字にマッチングさせて、そのマッチングの前の部分も
4776保持させてみましょう。
4777そしてあなたは次のように書くかもしれません。
4778
4779 $_ = "I have 2 numbers: 53147";
4780 if ( /(.*)(\d*)/ ) { # Wrong!
4781 print "Beginning is <$1>, number is <$2>.\n";
4782 }
4783
4784=begin original
4785
4786That won't work at all, because C<.*> was greedy and gobbled up the
4787whole string. As C<\d*> can match on an empty string the complete
4788regular expression matched successfully.
4789
4790=end original
4791
4792これは全く動作しません、なぜなら C<.*> は貪欲であり文字列全体を
4793飲み込んでしまいます。
4794C<\d*> は空の文字列にマッチングできるので正規表現は完全に正常に
4795マッチングします。
4796
4797 Beginning is <I have 2 numbers: 53147>, number is <>.
4798
4799=begin original
4800
4801Here are some variants, most of which don't work:
4802
4803=end original
4804
4805動作しない主なバリエーションをあげておきます:
4806
4807 $_ = "I have 2 numbers: 53147";
4808 @pats = qw{
4809 (.*)(\d*)
4810 (.*)(\d+)
4811 (.*?)(\d*)
4812 (.*?)(\d+)
4813 (.*)(\d+)$
4814 (.*?)(\d+)$
4815 (.*)\b(\d+)$
4816 (.*\D)(\d+)$
4817 };
4818
4819 for $pat (@pats) {
4820 printf "%-12s ", $pat;
4821 if ( /$pat/ ) {
4822 print "<$1> <$2>\n";
4823 } else {
4824 print "FAIL\n";
4825 }
4826 }
4827
4828=begin original
4829
4830That will print out:
4831
4832=end original
4833
4834これらの結果は次のようになります:
4835
4836 (.*)(\d*) <I have 2 numbers: 53147> <>
4837 (.*)(\d+) <I have 2 numbers: 5314> <7>
4838 (.*?)(\d*) <> <>
4839 (.*?)(\d+) <I have > <2>
4840 (.*)(\d+)$ <I have 2 numbers: 5314> <7>
4841 (.*?)(\d+)$ <I have 2 numbers: > <53147>
4842 (.*)\b(\d+)$ <I have 2 numbers: > <53147>
4843 (.*\D)(\d+)$ <I have 2 numbers: > <53147>
4844
4845=begin original
4846
4847As you see, this can be a bit tricky. It's important to realize that a
4848regular expression is merely a set of assertions that gives a definition
4849of success. There may be 0, 1, or several different ways that the
4850definition might succeed against a particular string. And if there are
4851multiple ways it might succeed, you need to understand backtracking to
4852know which variety of success you will achieve.
4853
4854=end original
4855
4856このように、これは幾分トリッキーです。
4857重要なのは正規表現は成功の定義を定める主張の集合にすぎないことを
4858認識することです。
4859特定の文字列で成功となる定義には 0, 1 または複数の違ったやり方が存在します。
4860そしてもし成功する複数の方法が存在するのなら成功したうちのどれが目的と
4861するものなのかを知るためにバックトラッキングを理解しておく必要があります。
4862
4863=begin original
4864
4865When using look-ahead assertions and negations, this can all get even
4866trickier. Imagine you'd like to find a sequence of non-digits not
4867followed by "123". You might try to write that as
4868
4869=end original
4870
4871前読みの言明及び否定を使っている時にはこれはますますトリッキーになります。
4872"123" が後ろに続かない数字以外の列を探したいと考えてみてください。
4873あなたは次のように書くかもしれません。
4874
4875 $_ = "ABC123";
4876 if ( /^\D*(?!123)/ ) { # Wrong!
4877 print "Yup, no 123 in $_\n";
4878 }
4879
4880=begin original
4881
4882But that isn't going to match; at least, not the way you're hoping. It
4883claims that there is no 123 in the string. Here's a clearer picture of
4884why that pattern matches, contrary to popular expectations:
4885
4886=end original
4887
4888ですがこれはマッチングしません; 少なくともなってほしかったようには。
4889これは文字列の中に 123 がないことを要求します。
4890よくある予想と比較してなぜパターンがマッチングするのかのわかりやすい
4891説明を次に示します:
4892
4893 $x = 'ABC123';
4894 $y = 'ABC445';
4895
4896 print "1: got $1\n" if $x =~ /^(ABC)(?!123)/;
4897 print "2: got $1\n" if $y =~ /^(ABC)(?!123)/;
4898
4899 print "3: got $1\n" if $x =~ /^(\D*)(?!123)/;
4900 print "4: got $1\n" if $y =~ /^(\D*)(?!123)/;
4901
4902=begin original
4903
4904This prints
4905
4906=end original
4907
4908これは次の出力となります
4909
4910 2: got ABC
4911 3: got AB
4912 4: got ABC
4913
4914=begin original
4915
4916You might have expected test 3 to fail because it seems to a more
4917general purpose version of test 1. The important difference between
4918them is that test 3 contains a quantifier (C<\D*>) and so can use
4919backtracking, whereas test 1 will not. What's happening is
4920that you've asked "Is it true that at the start of $x, following 0 or more
4921non-digits, you have something that's not 123?" If the pattern matcher had
4922let C<\D*> expand to "ABC", this would have caused the whole pattern to
4923fail.
4924
4925=end original
4926
4927テスト 3 はテスト 1 のより一般的なバージョンなのでそれが失敗すると
4928考えたかもしれません。
4929この 2 つの重要な違いは、テスト 3 には量指定子(C<\D*>)が含まれているので
4930テスト1ではできなかったバックトラッキングを行うことが
4931できるところにあります。
4932ここであなたは「$x のはじめで 0 個以上の非数字があるから 123 ではない
4933何かを得られるんじゃないの?」と聞くでしょう。
4934このパターンマッチングが C<\D*> を "ABC" に展開させると
4935これはパターン全体を失敗させることになります。
4936
4937=begin original
4938
4939The search engine will initially match C<\D*> with "ABC". Then it will
4940try to match C<(?!123)> with "123", which fails. But because
4941a quantifier (C<\D*>) has been used in the regular expression, the
4942search engine can backtrack and retry the match differently
4943in the hope of matching the complete regular expression.
4944
4945=end original
4946
4947探索エンジンは最初に C<\D*> を "ABC" にマッチングさせます。
4948そして C<(?!123)> を "123" にマッチングさせ、これは失敗します。
4949けれども量指定子 (C<\D*>) が正規表現の中で使われているので、探索エンジンは
4950バックトラックしてこの正規表現全体をマッチングさせるように異なるマッチングを
4951行うことができます。
4952
4953=begin original
4954
4955The pattern really, I<really> wants to succeed, so it uses the
4956standard pattern back-off-and-retry and lets C<\D*> expand to just "AB" this
4957time. Now there's indeed something following "AB" that is not
4958"123". It's "C123", which suffices.
4959
4960=end original
4961
4962このパターンは本当に、I<本当に> 成功したいので、これは標準的なパターンの
4963後退再試行を行い、この時に C<\D*> を "AB" のみに展開させます。
4964そして確かに "AB" の後ろは "123" ではありません。
4965"C123" は十分満たしています。
4966
4967=begin original
4968
4969We can deal with this by using both an assertion and a negation.
4970We'll say that the first part in $1 must be followed both by a digit
4971and by something that's not "123". Remember that the look-aheads
4972are zero-width expressions--they only look, but don't consume any
4973of the string in their match. So rewriting this way produces what
4974you'd expect; that is, case 5 will fail, but case 6 succeeds:
4975
4976=end original
4977
4978これは言明と否定の両方を使うことで処理することができます。
4979$1 の最初の部分は数字が続きかつそれは "123" ではないことを宣言します。
4980先読みはゼロ幅の式なのでそれがマッチングした文字列を全く消費しないことを
4981思い出してください。
4982そしてこれを必要なものを生成するように書き換えます;
4983つまり、5 のケースでは失敗し、6 のケースは成功します:
4984
4985 print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/;
4986 print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/;
4987
4988 6: got ABC
4989
4990=begin original
4991
4992In other words, the two zero-width assertions next to each other work as though
4993they're ANDed together, just as you'd use any built-in assertions: C</^$/>
4994matches only if you're at the beginning of the line AND the end of the
4995line simultaneously. The deeper underlying truth is that juxtaposition in
4996regular expressions always means AND, except when you write an explicit OR
4997using the vertical bar. C</ab/> means match "a" AND (then) match "b",
4998although the attempted matches are made at different positions because "a"
4999is not a zero-width assertion, but a one-width assertion.
5000
5001=end original
5002
5003言い換えると、このそれぞれの次にある2つのゼロ幅の言明はちょうど何か組み込みの
5004言明を使ったかのようにそれらがともに AND されているかのように動作します:
5005C</^$/> は行の始まりで且つ同時に行の終了でる時にのみマッチングします。
5006もっと深部での真実は、併記された正規表現は垂直線を使って明示的に OR を
5007書いたとき以外は常に AND を意味します。
5008C</ab/> は、"a" がゼロ幅の言明ではなく 1 文字幅の言明なので異なる場所で
5009マッチングが行われはしますが、 "a" にマッチング且つ(そして) "b" に
5010マッチングということを意味します。
5011
5012=begin original
5013
5014B<WARNING>: Particularly complicated regular expressions can take
5015exponential time to solve because of the immense number of possible
5016ways they can use backtracking to try for a match. For example, without
5017internal optimizations done by the regular expression engine, this will
5018take a painfully long time to run:
5019
5020=end original
5021
5022B<警告>: 特にコンパイルされた正規表現はマッチングのために
5023できる限りのバックトラックを非常に多くの回数行うので
5024解くために指数的な時間を必要とすることがあります。
5025例えば、正規表現エンジンの内部で行われる最適化がなかったときには、次の評価は
5026尋常じゃないくらい長時間かかります:
5027
5028 'aaaaaaaaaaaa' =~ /((a{0,5}){0,5})*[c]/
5029
5030=begin original
5031
5032And if you used C<*>'s in the internal groups instead of limiting them
5033to 0 through 5 matches, then it would take forever--or until you ran
5034out of stack space. Moreover, these internal optimizations are not
5035always applicable. For example, if you put C<{0,5}> instead of C<*>
5036on the external group, no current optimization is applicable, and the
5037match takes a long time to finish.
5038
5039=end original
5040
5041そしてもし内側のグループで 0 から 5 回にマッチングを制限する代わりに
5042C<*> を使うと、永久に、またはスタックを使い果たすまで
5043実行し続けることになります。
5044その上、これらの最適化は常にできるわけではありません。
5045例えば、外側のグループで C<*> の代わりに C<{0,5}> を使ったときに、現在の
5046最適化は適用されません; そしてマッチングが終わるまでの長い時間が
5047必要になります。
5048
5049=begin original
5050
5051A powerful tool for optimizing such beasts is what is known as an
5052"independent group",
5053which does not backtrack (see L</C<< (?>pattern) >>>). Note also that
5054zero-length look-ahead/look-behind assertions will not backtrack to make
5055the tail match, since they are in "logical" context: only
5056whether they match is considered relevant. For an example
5057where side-effects of look-ahead I<might> have influenced the
5058following match, see L</C<< (?>pattern) >>>.
5059
5060=end original
5061
5062そのような野獣のような最適化のためのパワフルなツールとして
5063知られているものに、「独立グループ」があります; これはバックトラックを
5064行いません (L</C<< (?>pattern) >>> を参照)。
5065ゼロ幅の先読み/後読みの言明も「論理的な」文脈なので末尾のマッチングを
5066バックトラックしません: マッチングが関連して考慮されるかどうかだけです。
5067先読みの言明の副作用がそれに続くマッチングに影響する I<かもしれない> 例は、
5068L</C<< (?>pattern) >>> を参照してください。
5069
5070=head2 Version 8 Regular Expressions
5071X<regular expression, version 8> X<regex, version 8> X<regexp, version 8>
5072
5073(バージョン 8 正規表現)
5074
5075=begin original
5076
5077In case you're not familiar with the "regular" Version 8 regex
5078routines, here are the pattern-matching rules not described above.
5079
5080=end original
5081
5082「通常の」バージョン 8 正規表現ルーチンに詳しくないのであれば、ここには
5083これまでに説明されていないパターンマッチングルールがあります。
5084
5085=begin original
5086
5087Any single character matches itself, unless it is a I<metacharacter>
5088with a special meaning described here or above. You can cause
5089characters that normally function as metacharacters to be interpreted
5090literally by prefixing them with a "\" (e.g., "\." matches a ".", not any
5091character; "\\" matches a "\"). This escape mechanism is also required
5092for the character used as the pattern delimiter.
5093
5094=end original
5095
5096すべての単一の文字は、それが個々でまたはこれまでに説明した特別な意味を
5097持っている I<メタ文字> である場合以外は、文字それ自身にマッチングします。
5098文字は "\" で前置されることで通常はメタ文字としての機能を持っている文字を
5099リテラルとして処理させれるようになります(つまり、"\." は任意の 1 文字ではなく
5100"." にマッチングするようになり、"\\" は "\" にマッチングするようになります。
5101このエスケープ機構はパターン区切りとして使われている文字でも必要です。
5102
5103=begin original
5104
5105A series of characters matches that series of characters in the target
5106string, so the pattern C<blurfl> would match "blurfl" in the target
5107string.
5108
5109=end original
5110
5111文字の並びは、ターゲット文字列の文字の並びにマッチングします; 従って
5112パターン C<blurfl> は、ターゲット文字列の "blurfl" にマッチングします。
5113
5114=begin original
5115
5116You can specify a character class, by enclosing a list of characters
5117in C<[]>, which will match any character from the list. If the
5118first character after the "[" is "^", the class matches any character not
5119in the list. Within a list, the "-" character specifies a
5120range, so that C<a-z> represents all characters between "a" and "z",
5121inclusive. If you want either "-" or "]" itself to be a member of a
5122class, put it at the start of the list (possibly after a "^"), or
5123escape it with a backslash. "-" is also taken literally when it is
5124at the end of the list, just before the closing "]". (The
5125following all specify the same class of three characters: C<[-az]>,
5126C<[az-]>, and C<[a\-z]>. All are different from C<[a-z]>, which
5127specifies a class containing twenty-six characters, even on EBCDIC-based
5128character sets.) Also, if you try to use the character
5129classes C<\w>, C<\W>, C<\s>, C<\S>, C<\d>, or C<\D> as endpoints of
5130a range, the "-" is understood literally.
5131
5132=end original
5133
5134C<[]> で文字のリストを囲むことで文字クラスを指定することができます;
5135これはリストの中の任意の文字にマッチングします。
5136もし "[" の後の最初の文字が "^" だったときには、その文字クラスは
5137リストの中にない任意の文字にマッチングします。
5138リストの中では、文字 "-" は範囲を意味します; なので C<a-z> は "a" と "z" を
5139含めてそれらの間にあるすべての文字を表現します。
5140文字クラスの要素として "-" または "]" を使いたい時には、リストの先頭に
5141(あるいは"^"の後に)置くか、バックスラッシュを使ってエスケープします。
5142"-" はリストの終端、リストを閉じる "]" の直前にあったときもリテラルとして
5143扱われます。
5144(次の例はすべて同じ3文字からなる文字クラスです: C<[-az]>, C<[az-]>,
5145C<[a\-z]>。
5146これらはすべて EBCDIC ベースの文字集合であっても26文字からなる文字集合
5147C<[a-z]> とは異なります。) また、範囲の端点として文字クラス C<\w>, C<\W>,
5148C<\s>, C<\S>, C<\d>, C<\D> を使ったときも "-" はリテラルとして
5149処理されます。
5150
5151=begin original
5152
5153Note also that the whole range idea is rather unportable between
5154character sets--and even within character sets they may cause results
5155you probably didn't expect. A sound principle is to use only ranges
5156that begin from and end at either alphabetics of equal case ([a-e],
5157[A-E]), or digits ([0-9]). Anything else is unsafe. If in doubt,
5158spell out the character sets in full.
5159
5160=end original
5161
5162範囲全体というアイデアは文字集合間でポータブルではありません -- そして
5163結果となる文字集合では予期したものではないでしょう。
5164ひとつの安全策としては同じケースの英字の([a-e], [A-E]),
5165または数字([0-9])という範囲でのみ使うことです。
5166これ以外は安全ではありません。
5167もし信じられないのであれば文字集合を完全につづってみてください。
5168
5169=begin original
5170
5171Characters may be specified using a metacharacter syntax much like that
5172used in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return,
5173"\f" a form feed, etc. More generally, \I<nnn>, where I<nnn> is a string
5174of three octal digits, matches the character whose coded character set value
5175is I<nnn>. Similarly, \xI<nn>, where I<nn> are hexadecimal digits,
5176matches the character whose ordinal is I<nn>. The expression \cI<x>
5177matches the character control-I<x>. Finally, the "." metacharacter
5178matches any character except "\n" (unless you use C</s>).
5179
5180=end original
5181
5182文字は C でよく使われているようなメタ文字の構文を使って指定することも
5183できます: "\n" は改行にマッチングし、"\t" はタブに、"\r" は復帰に、
5184"\f" はフォームフィードにといった具合にマッチングします。
5185より一般的に、\I<nnn> (I<nnn> は 3 桁の 8 進数字) はその文字集合でコード値
5186I<nnn> の文字にマッチングします。
5187同じように、\xI<nn> (I<nn> は16進数字) は数値で I<nn> になる文字に
5188マッチングします。
5189式 \cI<x> は制御文字 I<x> にマッチングします。
5190そして最後に、"." メタ文字は (C</s> を使っていない限り) "\n" 以外の任意の
5191文字にマッチングします。
5192
5193=begin original
5194
5195You can specify a series of alternatives for a pattern using "|" to
5196separate them, so that C<fee|fie|foe> will match any of "fee", "fie",
5197or "foe" in the target string (as would C<f(e|i|o)e>). The
5198first alternative includes everything from the last pattern delimiter
5199("(", "(?:", etc. or the beginning of the pattern) up to the first "|", and
5200the last alternative contains everything from the last "|" to the next
5201closing pattern delimiter. That's why it's common practice to include
5202alternatives in parentheses: to minimize confusion about where they
5203start and end.
5204
5205=end original
5206
5207"|" を使ってパターンを区切って一連の代替を指定することもできます; なので
5208C<fee|fie|foe> は対象の文字列の "fee"、"fie"、または "foe" のいずれかに
5209(C<f(e|i|o)e> のように)マッチングします。
5210最初の代替には最後のパターン区切り ("(", "(?:" など、またはパターンの始まり)から
5211最初の "|" までのすべてが含まれ、最後の代替には最後の "|" から
5212次の閉じパターン区切りまでが含まれます。
5213通常代替をかっこの中に入れるのは、その開始位置と終了位置が少しはわかりやすく
5214なるようにです。
5215
5216=begin original
5217
5218Alternatives are tried from left to right, so the first
5219alternative found for which the entire expression matches, is the one that
5220is chosen. This means that alternatives are not necessarily greedy. For
5221example: when matching C<foo|foot> against "barefoot", only the "foo"
5222part will match, as that is the first alternative tried, and it successfully
5223matches the target string. (This might not seem important, but it is
5224important when you are capturing matched text using parentheses.)
5225
5226=end original
5227
5228代替は左から右へと試されます、なので最初の代替がその完全な式で
5229マッチングしたのならそれが選択されます。
5230これは代替は貪欲である必要はないということを意味します。
5231例えば: "barefoot" に対して C<foo|foot> をマッチングさせると、最初の代替から
5232試されるので、"foo" の部分がマッチングし、これは対象の文字列に対して成功で
5233マッチングします。
5234(これは重要ではないでしょうが、かっこを使ってマッチングしたテキストを
5235捕捉しているときには重要でしょう。)
5236
5237=begin original
5238
5239Also remember that "|" is interpreted as a literal within square brackets,
5240so if you write C<[fee|fie|foe]> you're really only matching C<[feio|]>.
5241
5242=end original
5243
5244また "|" は角かっこの中ではリテラルとして処理されるので、
5245C<[fee|fie|foe]> と書くとこれは実際には C<[feio|]> にのみマッチングします。
5246
5247=begin original
5248
5249Within a pattern, you may designate subpatterns for later reference
5250by enclosing them in parentheses, and you may refer back to the
5251I<n>th subpattern later in the pattern using the metacharacter
5252\I<n> or \gI<n>. Subpatterns are numbered based on the left to right order
5253of their opening parenthesis. A backreference matches whatever
5254actually matched the subpattern in the string being examined, not
5255the rules for that subpattern. Therefore, C<(0|0x)\d*\s\g1\d*> will
5256match "0x1234 0x4321", but not "0x1234 01234", because subpattern
52571 matched "0x", even though the rule C<0|0x> could potentially match
5258the leading 0 in the second number.
5259
5260=end original
5261
5262パターンにおいて、後で参照するためにかっこで括って部分パターンを指定できます;
5263してメタ文字 \I<n> または \gI<n> を使ってパターンの後の方で I<n> 番目の
5264部分パターンを参照することができます。
5265部分パターンはその開きかっこの左から右への順に番号づけられます。
5266後方参照は評価された文字列の中でその部分パターンに実際にマッチングしたものに
5267マッチングします。
5268従って、C<(0|0x)\d*\s\g1\d*> は "0x1234 0x4321" にはマッチングしますが、
5269"0x1234 01234" にはマッチングしません; なぜなら、C<0|0x> は二つめ数字の
5270先頭にある 0 にマッチングすることができるのですが、
5271部分パターン 1 は "0x" にマッチングするためです。
5272
5273=head2 Warning on \1 Instead of $1
5274
5275($1 ではなく \1 だったときの警告)
5276
5277=begin original
5278
52796628Some people get too used to writing things like:
52806629
52816630=end original
52826631
52836632次のように書くことになれている人も中にはいるでしょう:
52846633
52856634 $pattern =~ s/(\W)/\\\1/g;
52866635
52876636=begin original
52886637
52896638This is grandfathered (for \1 to \9) for the RHS of a substitute to avoid
52906639shocking the
52916640B<sed> addicts, but it's a dirty habit to get into. That's because in
52926641PerlThink, the righthand side of an C<s///> is a double-quoted string. C<\1> in
52936642the usual double-quoted string means a control-A. The customary Unix
52946643meaning of C<\1> is kludged in for C<s///>. However, if you get into the habit
52956644of doing that, you get yourself into trouble if you then add an C</e>
52966645modifier.
52976646
52986647=end original
52996648
53006649(\1 から \9 については) B<sed> 中毒な人をびっくりさせないための RHS 置換の
53016650祖先ですが、しかしこれは汚らしい癖です。
53026651Perl においては、C<s///> の右側はダブルクォートされた文字列と
53036652考えられるためです。
53046653通常のダブルクォートされた文字列の中では C<\1> は control-A を意味します。
53056654C<\1> の Unix での習慣的な意味は C<s///> だけのその場しのぎです。
53066655しかしながら、この癖に漬かっていると C</e> 修飾子を使ったときに
53076656トラブルとなるでしょう。
53086657
53096658 s/(\d+)/ \1 + 1 /eg; # causes warning under -w
53106659
53116660=begin original
53126661
53136662Or if you try to do
53146663
53156664=end original
53166665
53176666または次のようにするかもしれません
53186667
53196668 s/(\d+)/\1000/;
53206669
53216670=begin original
53226671
53236672You can't disambiguate that by saying C<\{1}000>, whereas you can fix it with
53246673C<${1}000>. The operation of interpolation should not be confused
53256674with the operation of matching a backreference. Certainly they mean two
53266675different things on the I<left> side of the C<s///>.
53276676
53286677=end original
53296678
53306679これを解消するために C<\{1}000> としないでください;
53316680ここでは C<${1}000> とするべきです。
53326681埋め込みの処理は後方参照にマッチングさせる操作より混乱は少ないでしょう。
53336682特に C<s///> の I<左> 側では2つの異なった意味になります。
53346683
53356684=head2 Repeated Patterns Matching a Zero-length Substring
53366685
53376686(ゼロ幅の部分文字列にマッチングするパターンの繰り返し)
53386687
53396688=begin original
53406689
53416690B<WARNING>: Difficult material (and prose) ahead. This section needs a rewrite.
53426691
53436692=end original
53446693
53456694B<警告>: この先には難しい(そして無味乾燥な)内容があります。
53466695このセクションは書き直す必要があるでしょう。
53476696
53486697=begin original
53496698
53506699Regular expressions provide a terse and powerful programming language. As
53516700with most other power tools, power comes together with the ability
53526701to wreak havoc.
53536702
53546703=end original
53556704
53566705正規表現は簡潔でパワフルなプログラミング言語を提供します。
53576706他の多くの強力なツールとともに、力は破壊の源にもなります。
53586707
53596708=begin original
53606709
53616710A common abuse of this power stems from the ability to make infinite
53626711loops using regular expressions, with something as innocuous as:
53636712
53646713=end original
53656714
53666715この力のよくある乱用は無害な何かとともに、正規表現使った
53676716無限ループとなります。
53686717
53696718 'foo' =~ m{ ( o? )* }x;
53706719
53716720=begin original
53726721
5373The C<o?> matches at the beginning of C<'foo'>, and since the position
6722The C<o?> matches at the beginning of "C<foo>", and since the position
53746723in the string is not moved by the match, C<o?> would match again and again
5375because of the C<*> quantifier. Another common way to create a similar cycle
6724because of the C<"*"> quantifier. Another common way to create a similar cycle
5376is with the looping modifier C<//g>:
6725is with the looping modifier C</g>:
53776726
53786727=end original
53796728
5380C<o?> は C<'foo'> の始まりにマッチングし、文字列中での位置はこの
6729C<o?> は "C<foo>" の始まりにマッチングし、文字列中での位置はこの
5381マッチングでは動かないので、C<o?> は C<*> 量指定子によって何回も
6730マッチングでは動かないので、C<o?> は C<"*"> 量指定子によって何回も
53826731マッチングします。
5383同じような繰り返しを作るもう一つのよくある形として C<//g> 修飾子を使った
6732同じような繰り返しを作るもう一つのよくある形として C</g> 修飾子を使った
53846733ループがあります:
53856734
53866735 @matches = ( 'foo' =~ m{ o? }xg );
53876736
53886737=begin original
53896738
53906739or
53916740
53926741=end original
53936742
53946743または
53956744
53966745 print "match: <$&>\n" while 'foo' =~ m{ o? }xg;
53976746
53986747=begin original
53996748
5400or the loop implied by split().
6749or the loop implied by C<split()>.
54016750
54026751=end original
54036752
5404または split() による暗黙のループ。
6753または C<split()> による暗黙のループ。
54056754
54066755=begin original
54076756
54086757However, long experience has shown that many programming tasks may
54096758be significantly simplified by using repeated subexpressions that
54106759may match zero-length substrings. Here's a simple example being:
54116760
54126761=end original
54136762
54146763しかしながら、長きにわたる経験からいくつかのプログラミングタスクは
54156764ゼロ幅の部分文字列に対するマッチングを行う部分式の繰り返しで大幅に
54166765単純にできることがわかりました。
54176766簡単な例を挙げてみます:
54186767
54196768 @chars = split //, $string; # // is not magic in split
54206769 ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /
54216770
54226771=begin original
54236772
54246773Thus Perl allows such constructs, by I<forcefully breaking
54256774the infinite loop>. The rules for this are different for lower-level
54266775loops given by the greedy quantifiers C<*+{}>, and for higher-level
5427ones like the C</g> modifier or split() operator.
6776ones like the C</g> modifier or C<split()> operator.
54286777
54296778=end original
54306779
54316780このように Perl は I<強制的に無限ループを砕く> ことによってこういった構築を
54326781可能にしています。
54336782このためのルールは貪欲な量指定子 C<*+{}> によって与えられる
5434低レベルなループとも、C</g> 修飾子や split() 演算子による
6783低レベルなループとも、C</g> 修飾子や C<split()> 演算子による
54356784高レベルなループとも異なります。
54366785
54376786=begin original
54386787
54396788The lower-level loops are I<interrupted> (that is, the loop is
54406789broken) when Perl detects that a repeated expression matched a
54416790zero-length substring. Thus
54426791
54436792=end original
54446793
54456794低レベルなループは Perl がゼロ幅の部分文字列に対してマッチングする式が
54466795繰り返されたことを検出すると I<中断> されます (つまり、ループは壊されます)。
54476796従って
54486797
54496798 m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;
54506799
54516800=begin original
54526801
54536802is made equivalent to
54546803
54556804=end original
54566805
54576806は次と等価にされます
54586807
54596808 m{ (?: NON_ZERO_LENGTH )* (?: ZERO_LENGTH )? }x;
54606809
54616810=begin original
54626811
54636812For example, this program
54646813
54656814=end original
54666815
54676816例えば、以下のプログラムは
54686817
54696818 #!perl -l
54706819 "aaaaab" =~ /
54716820 (?:
54726821 a # non-zero
54736822 | # or
54746823 (?{print "hello"}) # print hello whenever this
54756824 # branch is tried
54766825 (?=(b)) # zero-width assertion
54776826 )* # any number of times
54786827 /x;
54796828 print $&;
54806829 print $1;
54816830
54826831=begin original
54836832
54846833prints
54856834
54866835=end original
54876836
54886837以下を表示します
54896838
54906839 hello
54916840 aaaaa
54926841 b
54936842
54946843=begin original
54956844
54966845Notice that "hello" is only printed once, as when Perl sees that the sixth
54976846iteration of the outermost C<(?:)*> matches a zero-length string, it stops
5498the C<*>.
6847the C<"*">.
54996848
55006849=end original
55016850
55026851"hello" は一度だけ表示されることに注目して下さい; Perl は
55036852一番外側の C<(?:)*> の 6 回目の繰り返しがゼロ長文字列にマッチングするのを
5504見るので、C<*> を止めます。
6853見るので、C<"*"> を止めます。
55056854
55066855=begin original
55076856
55086857The higher-level loops preserve an additional state between iterations:
55096858whether the last match was zero-length. To break the loop, the following
55106859match after a zero-length match is prohibited to have a length of zero.
5511This prohibition interacts with backtracking (see L<"Backtracking">),
6860This prohibition interacts with backtracking (see L</"Backtracking">),
55126861and so the I<second best> match is chosen if the I<best> match is of
55136862zero length.
55146863
55156864=end original
55166865
55176866高レベルのループは各繰り返しの間に最後のマッチングがゼロ幅だったかどうかを
55186867追加で保持しています。
55196868ループを終えるために、ゼロ幅のマッチングの後のマッチングはゼロ幅と
55206869なることを拒否します。
5521この禁則処理はバックトラックと相互に動作し(L<"Backtracking"> 参照)、そして
6870この禁則処理はバックトラックと相互に動作し(L</"Backtracking"> 参照)、そして
55226871I<ベストな> マッチングがゼロ幅だったのなら I<2 番目にベストな>
55236872マッチングが選択されます。
55246873
55256874=begin original
55266875
55276876For example:
55286877
55296878=end original
55306879
55316880例:
55326881
55336882 $_ = 'bar';
55346883 s/\w??/<$&>/g;
55356884
55366885=begin original
55376886
55386887results in C<< <><b><><a><><r><> >>. At each position of the string the best
55396888match given by non-greedy C<??> is the zero-length match, and the I<second
55406889best> match is what is matched by C<\w>. Thus zero-length matches
55416890alternate with one-character-long matches.
55426891
55436892=end original
55446893
55456894これは C<< <><b><><a><><r><> >> となります。
55466895文字列の各位置に於いて、貪欲でない C<??> によって得られるベストな
55476896マッチングはゼロ幅のマッチングです、
55486897そして I<2 番目にベストな>マッチングは C<\w> によってマッチングするものです。
55496898従ってゼロ幅のマッチングは 1 文字幅のマッチングの代替となります。
55506899
55516900=begin original
55526901
55536902Similarly, for repeated C<m/()/g> the second-best match is the match at the
55546903position one notch further in the string.
55556904
55566905=end original
55576906
55586907同じように、C<m/()/g> の繰り返しでは文字列中の境界一つ遠い位置に 2 番目に
55596908ベストなマッチングがマッチングします。
55606909
55616910=begin original
55626911
55636912The additional state of being I<matched with zero-length> is associated with
5564the matched string, and is reset by each assignment to pos().
6913the matched string, and is reset by each assignment to C<pos()>.
55656914Zero-length matches at the end of the previous match are ignored
55666915during C<split>.
55676916
55686917=end original
55696918
55706919I<ゼロ幅にマッチングしている> という追加の状態はマッチングした文字列に
5571関連づけられていて、pos() に対する割り当てによってリセットされます。
6920関連づけられていて、C<pos()> に対する割り当てによってリセットされます。
55726921前のマッチングの終端でのゼロ幅のマッチングは C<split> の間は無視されます。
55736922
55746923=head2 Combining RE Pieces
55756924
55766925(RE の欠片の結合)
55776926
55786927=begin original
55796928
55806929Each of the elementary pieces of regular expressions which were described
55816930before (such as C<ab> or C<\Z>) could match at most one substring
55826931at the given position of the input string. However, in a typical regular
55836932expression these elementary pieces are combined into more complicated
5584patterns using combining operators C<ST>, C<S|T>, C<S*> etc.
6933patterns using combining operators C<ST>, C<S|T>, C<S*> I<etc>.
5585(in these examples C<S> and C<T> are regular subexpressions).
6934(in these examples C<"S"> and C<"T"> are regular subexpressions).
55866935
55876936=end original
55886937
55896938これまでに説明された (C<ab> や C<\Z> といった) 正規表現の基本的な欠片
55906939それぞれは、入力文字列上の与えられた位置で多くとも1つの部分文字列に
55916940マッチングします。
55926941しかしながら、典型的な正規表現ではこれらの基本的な欠片は結合演算
5593C<ST>、C<S|T>、C<S*> 等(ここで C<S> や C<T> は正規表現の部分式)を使って
6942C<ST>、C<S|T>、C<S*> 等(ここで C<"S"> や C<"T"> は正規表現の部分式)を使って
55946943より複雑なパターンへと合成することができます。
55956944
55966945=begin original
55976946
55986947Such combinations can include alternatives, leading to a problem of choice:
55996948if we match a regular expression C<a|ab> against C<"abc">, will it match
56006949substring C<"a"> or C<"ab">? One way to describe which substring is
5601actually matched is the concept of backtracking (see L<"Backtracking">).
6950actually matched is the concept of backtracking (see L</"Backtracking">).
56026951However, this description is too low-level and makes you think
56036952in terms of a particular implementation.
56046953
56056954=end original
56066955
56076956このような合成には選択の問題を導くために代替を含めることができます:
56086957正規表現 C<a|ab> を C<"abc"> に対してマッチングさせようとしたとき、これは
56096958C<"a"> と C<"ab"> のどちらにマッチングするのか?
56106959実際にどちらがマッチングするのかを説明する1つの方法として、
5611バックトラッキングのコンセプトがあります(L<"Backtracking"> 参照)。
6960バックトラッキングのコンセプトがあります(L</"Backtracking"> 参照)。
56126961しかしながら、この説明は低レベルすぎて特定の実装を考えなければなりません。
56136962
56146963=begin original
56156964
56166965Another description starts with notions of "better"/"worse". All the
56176966substrings which may be matched by the given regular expression can be
56186967sorted from the "best" match to the "worst" match, and it is the "best"
56196968match which is chosen. This substitutes the question of "what is chosen?"
56206969by the question of "which matches are better, and which are worse?".
56216970
56226971=end original
56236972
56246973もう一つの説明は"より良い"/"より悪い"の考え方で始めます。
56256974与えられた正規表現にマッチングするすべての部分文字列は「最良の」
56266975マッチングから「最悪の」マッチングへとソートすることができます; そして
56276976「最良の」マッチングが選択されます。
56286977これは「どれが選ばれるのか?」という問いかけを「どのマッチングがより良くて、
56296978それがより悪いのか?」という問いかけに置き換えることができます。
56306979
56316980=begin original
56326981
56336982Again, for elementary pieces there is no such question, since at most
56346983one match at a given position is possible. This section describes the
56356984notion of better/worse for combining operators. In the description
5636below C<S> and C<T> are regular subexpressions.
6985below C<"S"> and C<"T"> are regular subexpressions.
56376986
56386987=end original
56396988
56406989そして、基本的な要素ではそういった問いかけはありません;
56416990なぜならこれらは与えられた位置で可能なマッチングは多くとも1つだからです。
56426991このセクションでは結合演算のより良い/より悪いの考え方で説明していきます。
5643以下の説明では C<S> 及び C<T> は正規表現の部分式です。
6992以下の説明では C<"S"> 及び C<"T"> は正規表現の部分式です。
56446993
56456994=over 4
56466995
56476996=item C<ST>
56486997
56496998=begin original
56506999
5651Consider two possible matches, C<AB> and C<A'B'>, C<A> and C<A'> are
7000Consider two possible matches, C<AB> and C<A'B'>, C<"A"> and C<A'> are
5652substrings which can be matched by C<S>, C<B> and C<B'> are substrings
7001substrings which can be matched by C<"S">, C<"B"> and C<B'> are substrings
5653which can be matched by C<T>.
7002which can be matched by C<"T">.
56547003
56557004=end original
56567005
565770062つの可能なマッチング、C<AB> 及び C<A'B'> を考えます;
5658ここで C<A> 及び C<A'> は C<S> にマッチングする部分文字列、
7007ここで C<"A"> 及び C<A'> は C<"S"> にマッチングする部分文字列、
5659そして C<B> 及び C<B'> は C<T> にマッチングする部分文字列とします。
7008そして C<"B"> 及び C<B'> は C<"T"> にマッチングする部分文字列とします。
56607009
56617010=begin original
56627011
5663If C<A> is a better match for C<S> than C<A'>, C<AB> is a better
7012If C<"A"> is a better match for C<"S"> than C<A'>, C<AB> is a better
56647013match than C<A'B'>.
56657014
56667015=end original
56677016
5668もし C<A> が C<S> に対して C<A'> よりも良いマッチングであれば、
7017もし C<"A"> が C<"S"> に対して C<A'> よりも良いマッチングであれば、
56697018C<AB> は C<A'B'> よりも良いマッチングです。
56707019
56717020=begin original
56727021
5673If C<A> and C<A'> coincide: C<AB> is a better match than C<AB'> if
7022If C<"A"> and C<A'> coincide: C<AB> is a better match than C<AB'> if
5674C<B> is a better match for C<T> than C<B'>.
7023C<"B"> is a better match for C<"T"> than C<B'>.
56757024
56767025=end original
56777026
5678もし C<A> と C<A'> が同じであれば: C<B> が C<T> に対して C<B'> よりも
7027もし C<"A"> と C<A'> が同じであれば: C<"B"> が C<"T"> に対して C<B'> よりも
56797028良いマッチングであれば C<AB> は C<AB'> よりも良いマッチングです。
56807029
56817030=item C<S|T>
56827031
56837032=begin original
56847033
5685When C<S> can match, it is a better match than when only C<T> can match.
7034When C<"S"> can match, it is a better match than when only C<"T"> can match.
56867035
56877036=end original
56887037
5689C<S> がマッチングできる時は C<T> のみがマッチングするよりも良い
7038C<"S"> がマッチングできる時は C<"T"> のみがマッチングするよりも良い
56907039マッチングです。
56917040
56927041=begin original
56937042
5694Ordering of two matches for C<S> is the same as for C<S>. Similar for
7043Ordering of two matches for C<"S"> is the same as for C<"S">. Similar for
5695two matches for C<T>.
7044two matches for C<"T">.
56967045
56977046=end original
56987047
5699C<S> に対する2つのマッチングの順序は C<S> と同じです。
7048C<"S"> に対する2つのマッチングの順序は C<"S"> と同じです。
5700C<T> に対する2つのマッチングも同様です。
7049C<"T"> に対する2つのマッチングも同様です。
57017050
57027051=item C<S{REPEAT_COUNT}>
57037052
57047053=begin original
57057054
57067055Matches as C<SSS...S> (repeated as many times as necessary).
57077056
57087057=end original
57097058
57107059C<SSS...S> (必要なだけ繰り返し)としてマッチングします。
57117060
57127061=item C<S{min,max}>
57137062
57147063=begin original
57157064
57167065Matches as C<S{max}|S{max-1}|...|S{min+1}|S{min}>.
57177066
57187067=end original
57197068
57207069C<S{max}|S{max-1}|...|S{min+1}|S{min}> としてマッチングします。
57217070
57227071=item C<S{min,max}?>
57237072
57247073=begin original
57257074
57267075Matches as C<S{min}|S{min+1}|...|S{max-1}|S{max}>.
57277076
57287077=end original
57297078
57307079C<S{min}|S{min+1}|...|S{max-1}|S{max}> としてマッチングします。
57317080
57327081=item C<S?>, C<S*>, C<S+>
57337082
57347083=begin original
57357084
57367085Same as C<S{0,1}>, C<S{0,BIG_NUMBER}>, C<S{1,BIG_NUMBER}> respectively.
57377086
57387087=end original
57397088
57407089それぞれ C<S{0,1}>, C<S{0,BIG_NUMBER}>, C<S{1,BIG_NUMBER}> と同じです。
57417090
57427091=item C<S??>, C<S*?>, C<S+?>
57437092
57447093=begin original
57457094
57467095Same as C<S{0,1}?>, C<S{0,BIG_NUMBER}?>, C<S{1,BIG_NUMBER}?> respectively.
57477096
57487097=end original
57497098
57507099それぞれ C<S{0,1}?>, C<S{0,BIG_NUMBER}?>, C<S{1,BIG_NUMBER}?> と同じです。
57517100
57527101=item C<< (?>S) >>
57537102
57547103=begin original
57557104
5756Matches the best match for C<S> and only that.
7105Matches the best match for C<"S"> and only that.
57577106
57587107=end original
57597108
5760C<S> の最良のみマッチングします。
7109C<"S"> の最良のみマッチングします。
57617110
57627111=item C<(?=S)>, C<(?<=S)>
57637112
57647113=begin original
57657114
5766Only the best match for C<S> is considered. (This is important only if
7115Only the best match for C<"S"> is considered. (This is important only if
5767C<S> has capturing parentheses, and backreferences are used somewhere
7116C<"S"> has capturing parentheses, and backreferences are used somewhere
57687117else in the whole regular expression.)
57697118
57707119=end original
57717120
5772C<S> の最良のマッチングのみが考慮されます。
7121C<"S"> の最良のマッチングのみが考慮されます。
5773(これは C<S> がキャプチャかっこを持っていて、そして正規表現全体の
7122(これは C<"S"> がキャプチャかっこを持っていて、そして正規表現全体の
57747123どこかで後方参照が使われている時のみ重要です.)
57757124
57767125=item C<(?!S)>, C<(?<!S)>
57777126
57787127=begin original
57797128
57807129For this grouping operator there is no need to describe the ordering, since
5781only whether or not C<S> can match is important.
7130only whether or not C<"S"> can match is important.
57827131
57837132=end original
57847133
5785このグループ演算子では、C<S> がマッチングできるかどうかのみが重要なので、
7134このグループ演算子では、C<"S"> がマッチングできるかどうかのみが重要なので、
57867135順序についての説明は必要ありません。
57877136
5788=item C<(??{ EXPR })>, C<(?PARNO)>
7137=item C<(??{ EXPR })>, C<(?I<PARNO>)>
57897138
57907139=begin original
57917140
57927141The ordering is the same as for the regular expression which is
5793the result of EXPR, or the pattern contained by capture group PARNO.
7142the result of EXPR, or the pattern contained by capture group I<PARNO>.
57947143
57957144=end original
57967145
5797順序は EXPR の結果の正規表現、または捕捉グループ PARNO に含まれている
7146順序は EXPR の結果の正規表現、または捕捉グループ I<PARNO> に含まれている
57987147パターンと同じです。
57997148
58007149=item C<(?(condition)yes-pattern|no-pattern)>
58017150
58027151=begin original
58037152
58047153Recall that which of C<yes-pattern> or C<no-pattern> actually matches is
58057154already determined. The ordering of the matches is the same as for the
58067155chosen subexpression.
58077156
58087157=end original
58097158
58107159既に決定している C<yes-pattern> または C<no-pattern> を実際に
58117160マッチングさせます。
58127161マッチングの順序は選択された部分式と同じです。
58137162
58147163=back
58157164
58167165=begin original
58177166
58187167The above recipes describe the ordering of matches I<at a given position>.
58197168One more rule is needed to understand how a match is determined for the
58207169whole regular expression: a match at an earlier position is always better
58217170than a match at a later position.
58227171
58237172=end original
58247173
58257174ここにあげたレシピはI<与えられた位置での>マッチングの順序について
58267175説明しています。
58277176正規表現全体でマッチングがどのように決定されるかを理解するためには
58287177もう少しルールが必要です:
58297178より若い位置でのマッチングは後ろの方でのマッチングよりもより良いです。
58307179
58317180=head2 Creating Custom RE Engines
58327181
58337182(カスタム RE エンジンの作成)
58347183
58357184=begin original
58367185
58377186As of Perl 5.10.0, one can create custom regular expression engines. This
58387187is not for the faint of heart, as they have to plug in at the C level. See
58397188L<perlreapi> for more details.
58407189
58417190=end original
58427191
58437192Perl 5.10.0 から、誰でもカスタム正規表現エンジンを作成できます。
58447193これは気弱な人向けではありません; C レベルでプラグインする必要があるからです。
58457194さらなる詳細については L<perlreapi> を参照して下さい。
58467195
58477196=begin original
58487197
58497198As an alternative, overloaded constants (see L<overload>) provide a simple
58507199way to extend the functionality of the RE engine, by substituting one
58517200pattern for another.
58527201
58537202=end original
58547203
58557204代替案として、オーバーロードされた定数(L<overload> 参照)は
58567205あるパターンを別のパターンに置き換えることで、RE エンジンの機能を
58577206拡張する簡単な方法を提供します。
58587207
58597208=begin original
58607209
58617210Suppose that we want to enable a new RE escape-sequence C<\Y|> which
58627211matches at a boundary between whitespace characters and non-whitespace
58637212characters. Note that C<(?=\S)(?<!\S)|(?!\S)(?<=\S)> matches exactly
58647213at these positions, so we want to have each C<\Y|> in the place of the
58657214more complicated version. We can create a module C<customre> to do
58667215this:
58677216
58687217=end original
58697218
58707219新しい正規表現エスケープシーケンス、空白文字と非空白文字との
58717220境界にマッチングする C<\Y|> を作ってみることにします。
58727221この位置には実際には C<(?=\S)(?<!\S)|(?!\S)(?<=\S)> がマッチングするので、
58737222この複雑なバージョンを C<\Y|> で置き換えたいとします。
58747223このために C<customre> モジュールを作ります:
58757224
58767225 package customre;
58777226 use overload;
58787227
58797228 sub import {
58807229 shift;
58817230 die "No argument to customre::import allowed" if @_;
58827231 overload::constant 'qr' => \&convert;
58837232 }
58847233
58857234 sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}
58867235
58877236 # We must also take care of not escaping the legitimate \\Y|
58887237 # sequence, hence the presence of '\\' in the conversion rules.
58897238 my %rules = ( '\\' => '\\\\',
58907239 'Y|' => qr/(?=\S)(?<!\S)|(?!\S)(?<=\S)/ );
58917240 sub convert {
58927241 my $re = shift;
58937242 $re =~ s{
58947243 \\ ( \\ | Y . )
58957244 }
58967245 { $rules{$1} or invalid($re,$1) }sgex;
58977246 return $re;
58987247 }
58997248
59007249=begin original
59017250
59027251Now C<use customre> enables the new escape in constant regular
5903expressions, i.e., those without any runtime variable interpolations.
7252expressions, I<i.e.>, those without any runtime variable interpolations.
59047253As documented in L<overload>, this conversion will work only over
59057254literal parts of regular expressions. For C<\Y|$re\Y|> the variable
59067255part of this regular expression needs to be converted explicitly
5907(but only if the special meaning of C<\Y|> should be enabled inside $re):
7256(but only if the special meaning of C<\Y|> should be enabled inside C<$re>):
59087257
59097258=end original
59107259
59117260これで C<use customre> することで正規表現定数の中で新しいエスケープを
59127261使うことが出来ます; すなわち、これには何の実行時変数の埋め込みもいりません。
59137262L<overload> に書かれているように、この変換は正規表現のリテラル部分にのみ
59147263動作します。
59157264C<\Y|$re\Y|> であればこの正規表現の変数部分は明示的に変換する
5916必要があります(とはいえ $re の中でも C<\Y|> を有効にしたい時のみ)。
7265必要があります(とはいえ C<$re> の中でも C<\Y|> を有効にしたい時のみ)。
59177266
59187267 use customre;
59197268 $re = <>;
59207269 chomp $re;
59217270 $re = customre::convert $re;
59227271 /\Y|$re\Y|/;
59237272
7273=head2 Embedded Code Execution Frequency
7274
7275(組み込みコードの実行頻度)
7276
7277=begin original
7278
7279The exact rules for how often C<(??{})> and C<(?{})> are executed in a pattern
7280are unspecified. In the case of a successful match you can assume that
7281they DWIM and will be executed in left to right order the appropriate
7282number of times in the accepting path of the pattern as would any other
7283meta-pattern. How non-accepting pathways and match failures affect the
7284number of times a pattern is executed is specifically unspecified and
7285may vary depending on what optimizations can be applied to the pattern
7286and is likely to change from version to version.
7287
7288=end original
7289
7290パターン中で C<(??{})> と C<(?{})> がどれくらいの頻度で実行されるかの
7291正確な規則は未規定です。
7292マッチングが成功した場合、それらは DWIM を行い、
7293他のメタパターンと同様、
7294パターンの受け入れられたパスの中で左から右の順序で適切な回数
7295実行されることを仮定できます。
7296受け入れられなかったパスとマッチングの失敗がどれくらいパターンの実行回数に
7297影響を与えるかは明確に非規定で、
7298パターンにどの最適化が適用できるかに依存し、バージョン毎に
7299変わる可能性が高いです。
7300
7301=begin original
7302
7303For instance in
7304
7305=end original
7306
7307例えば:
7308
7309 "aaabcdeeeee"=~/a(?{print "a"})b(?{print "b"})cde/;
7310
7311=begin original
7312
7313the exact number of times "a" or "b" are printed out is unspecified for
7314failure, but you may assume they will be printed at least once during
7315a successful match, additionally you may assume that if "b" is printed,
7316it will be preceded by at least one "a".
7317
7318=end original
7319
7320失敗時に "a" や "b" が何回表示されるかは未規定ですが、
7321マッチングに成功したときに少なくとも 1 回表示されることは仮定でき、
7322さらに "b" が表示されるとき、その前には少なくとも 1 回 "a" が
7323表示されることも仮定できます。
7324
7325=begin original
7326
7327In the case of branching constructs like the following:
7328
7329=end original
7330
7331次のような分岐構文の場合:
7332
7333 /a(b|(?{ print "a" }))c(?{ print "c" })/;
7334
7335=begin original
7336
7337you can assume that the input "ac" will output "ac", and that "abc"
7338will output only "c".
7339
7340=end original
7341
7342入力が "ac" なら出力は "ac"、入力が "abc" なら出力は
7343"c" だけと仮定できます。
7344
7345=begin original
7346
7347When embedded code is quantified, successful matches will call the
7348code once for each matched iteration of the quantifier. For
7349example:
7350
7351=end original
7352
7353組み込みコードが量指定された場合、マッチングに成功すると
7354量指定子のそれぞれのマッチングした反復毎に 1 回コードを呼び出します。
7355例えば:
7356
7357 "good" =~ /g(?:o(?{print "o"}))*d/;
7358
7359=begin original
7360
7361will output "o" twice.
7362
7363=end original
7364
7365これは "o" を 2 回出力します。
7366
59247367=head2 PCRE/Python Support
59257368
59267369(PCRE/Python サポート)
59277370
59287371=begin original
59297372
59307373As of Perl 5.10.0, Perl supports several Python/PCRE-specific extensions
59317374to the regex syntax. While Perl programmers are encouraged to use the
59327375Perl-specific syntax, the following are also accepted:
59337376
59347377=end original
59357378
59367379Perl 5.10.0 時点では Perl は幾つかの Python/PCRE 的な正規表現構文拡張を
59377380サポートします。
59387381Perl プログラマはこれらの Perl としての構文を推奨しますが、以下のものも
59397382受理されます:
59407383
59417384=over 4
59427385
59437386=item C<< (?PE<lt>NAMEE<gt>pattern) >>
59447387
59457388=begin original
59467389
59477390Define a named capture group. Equivalent to C<< (?<NAME>pattern) >>.
59487391
59497392=end original
59507393
59517394名前付の捕捉グループの定義。
59527395C<< (?<NAME>pattern) >> と等価。
59537396
59547397=item C<< (?P=NAME) >>
59557398
59567399=begin original
59577400
59587401Backreference to a named capture group. Equivalent to C<< \g{NAME} >>.
59597402
59607403=end original
59617404
59627405名前付捕捉グループへの後方参照。
59637406C<< \g{NAME} >> と等価。
59647407
59657408=item C<< (?P>NAME) >>
59667409
59677410=begin original
59687411
59697412Subroutine call to a named capture group. Equivalent to C<< (?&NAME) >>.
59707413
59717414=end original
59727415
59737416名前付き捕捉グループへの関数呼び出し。
59747417C<< (?&NAME) >> と等価。
59757418
59767419=back
59777420
59787421=head1 BUGS
59797422
59807423=begin original
59817424
5982Many regular expression constructs don't work on EBCDIC platforms.
5983
5984=end original
5985
5986多くの正規表現構文は EBCDIC プラットフォームでは動作しません。
5987
5988=begin original
5989
59907425There are a number of issues with regard to case-insensitive matching
5991in Unicode rules. See C<i> under L</Modifiers> above.
7426in Unicode rules. See C<"i"> under L</Modifiers> above.
59927427
59937428=end original
59947429
59957430Unicode ルールでの大文字小文字を無視したマッチングには多くの問題が
59967431あります。
5997上述の L</Modifiers> の C<i> を参照してください。
7432上述の L</Modifiers> の C<"i"> を参照してください。
59987433
59997434=begin original
60007435
60017436This document varies from difficult to understand to completely
60027437and utterly opaque. The wandering prose riddled with jargon is
60037438hard to fathom in several places.
60047439
60057440=end original
60067441
60077442この文書は、理解が困難なところから、完全かつ徹底的に不明瞭なところまで
60087443さまざまです。
60097444jargon に満ちたとりとめのない散文は幾つかの箇所で理解するのに
60107445難儀ではあるでしょう。
60117446
60127447=begin original
60137448
60147449This document needs a rewrite that separates the tutorial content
60157450from the reference content.
60167451
60177452=end original
60187453
60197454この文書はリファレンス的な内容からチュートリアル的な内容を分離して
60207455書き直す必要があります。
60217456
60227457=head1 SEE ALSO
7458
7459=begin original
7460
7461The syntax of patterns used in Perl pattern matching evolved from those
7462supplied in the Bell Labs Research Unix 8th Edition (Version 8) regex
7463routines. (The code is actually derived (distantly) from Henry
7464Spencer's freely redistributable reimplementation of those V8 routines.)
7465
7466=end original
7467
7468Perl のパターンマッチングで使われる文法は、
7469the Bell Labs Research Unix 8th Edition (Version 8) 正規表現ルーチンで
7470提供されているものからの派生です。
7471(コードは実際には Henry Spencer の自由に再配布可能な V8 ルーチンの再実装から
7472(遠く)派生しています)。
60237473
60247474L<perlrequick>.
60257475
60267476L<perlretut>.
60277477
60287478L<perlop/"Regexp Quote-Like Operators">.
60297479
60307480L<perlop/"Gory details of parsing quoted constructs">.
60317481
60327482L<perlfaq6>.
60337483
60347484L<perlfunc/pos>.
60357485
60367486L<perllocale>.
60377487
60387488L<perlebcdic>.
60397489
60407490=begin original
60417491
60427492I<Mastering Regular Expressions> by Jeffrey Friedl, published
60437493by O'Reilly and Associates.
60447494
60457495=end original
60467496
60477497O'Reilly and Associates から出版されている、Jeffrey Friedl による
60487498I<Mastering Regular Expressions> (詳説 正規表現)
60497499
60507500=begin meta
60517501
60527502Translate: 山科 氷魚 (YAMASHINA Hio) <hio@hio.jp> (5.10.0)
60537503Update: SHIRAKATA Kentaro <argrath@ub32.org> (5.10.1-)
60547504Status: completed
60557505
60567506=end meta