perlre - Perl 正規表現
perlre - Perl regular expressions

目次 TABLE OF CONTENTS


NAME

perlre - Perl 正規表現 perlre - Perl regular expressions


説明 DESCRIPTION

このページでは Perl での正規表現の構文について説明します. This page describes the syntax of regular expressions in Perl.

もしこれまでに正規表現を使ったことがないのであれば, perlrequickにクイックスタートが, perlretut に 長めのチュートリアルがあります. If you haven't used regular expressions before, a quick-start introduction is available in perlrequick, and a longer tutorial introduction is available in perlretut.

正規表現をマッチ操作でどのように使うかやそれに関する様々な例に 関しては, perlop 内 "Regexp Quote-Like Operators" にある m//, s///, qr// 及び ?? の説明を参照して下さい. For reference on how regular expressions are used in matching operations, plus various examples of the same, see discussions of m//, s///, qr// and ?? in "Regexp Quote-Like Operators" in perlop. >

修飾子 Modifiers

マッチ操作には様々な修飾子(modifier)があります. 修飾子は 正規表現内の解釈に関連する物で, 次に一覧にしています. Perl が 正規表現を使う方法を変更する修飾子は perlop 内 "Regexp Quote-Like Operators" 及び perlop 内 "Gory details of parsing quoted constructs" に 説明されています. Matching operations can have various modifiers. Modifiers that relate to the interpretation of the regular expression inside are listed below. Modifiers that alter the way a regular expression is used by Perl are detailed in "Regexp Quote-Like Operators" in perlop and "Gory details of parsing quoted constructs" in perlop.

m

文字列を複数行として扱います. つまり, "^" 及び "$" は 文字列の最初と最後に対するマッチから, 文字列中の各行の先頭と末尾に 対するマッチへと変更されます. Treat string as multiple lines. That is, change "^" and "$" from matching the start or end of the string to matching the start or end of any line anywhere within the string.

s

文字列を1行として扱います. つまり, "." は任意の1文字, 通常はマッチしない改行でさえもマッチするように変更されます. Treat string as single line. That is, change "." to match any character whatsoever, even a newline, which normally it would not match.

/ms として共に使うと, "^" 及び "$" はそれぞれ 文字列中の改行の直前及び直後のマッチでありつつ, "." は任意の文字に マッチするようになります. Used together, as /ms, they let the "." match any character whatsoever, while still allowing "^" and "$" to match, respectively, just after and just before newlines within the string.

i

大文字小文字を区別しないパターンマッチを行います. Do case-insensitive pattern matching.

use locale が有効になっている場合には大文字小文字の対応表は 現在のロケールから取られます. perllocale を参照してください. If use locale is in effect, the case map is taken from the current locale. See perllocale.

x

空白やコメントを許可してパターンを読みやすくするように拡張します. Extend your pattern's legibility by permitting whitespace and comments.

p

${^PREMATCH}, {$^MATCH}, 及び ${^POSTMATCH} といったマッチされた 文字列をマッチの後も使えるように維持します. Preserve the string matched such that ${^PREMATCH}, {$^MATCH}, and ${^POSTMATCH} are available for use after matching.

これらは通常 "/x 修飾子" のように記述され, これは区切りがスラッシュ でなくてもそう記述されます. また, これらはいずれも (?...) 構築子 を使って正規表現内に埋め込まれることもあります. These are usually written as "the /x modifier", even though the delimiter in question might not really be a slash. Any of these modifiers may also be embedded within the regular expression itself using the (?...) construct. See below.

/x に関してはもう少し説明が必要です. これはバックスラッシュで エスケープされているか文字クラスの中にあるか以外の空白文字を 無視するように正規表現パーサに伝えます. これを使うことで正規表現を (若干)より読みやすいパーツに分解することができます. そして # 文字は通常の Perl コードのようにコメントを始めるメタ文字として 扱われるようになります. これはパターンの中(それも/xの影響を 受けない文字クラスの外)で実際に空白や # 文字を必要とする ときには, エスケープするか8進数若しくは16進数エスケープ(バック スラッシュ若しくは \Q...\E)をしなければ なりません. /x でこれらの機能を利用することで, Perl の 正規表現をより読み易くするのに非常に役立ちます. ただ, コメントの 中にパターン区切り子を書いてしまわないようには注意してください -- perl にはパターンを早めに終わらせようとした訳じゃないことを 知る方法がないのです. C スタイルのコメントを削除するコードは perlop を参照してください. また \Q...\E の内側に なる箇所は /x の影響を受けないことに注意してください. The /x modifier itself needs a little more explanation. It tells the regular expression parser to ignore whitespace that is neither backslashed nor within a character class. You can use this to break up your regular expression into (slightly) more readable parts. The # character is also treated as a metacharacter introducing a comment, just as in ordinary Perl code. This also means that if you want real whitespace or # characters in the pattern (outside a character class, where they are unaffected by /x), then you'll either have to escape them (using backslashes or \Q...\E) or encode them using octal or hex escapes. Taken together, these features go a long way towards making Perl's regular expressions more readable. Note that you have to be careful not to include the pattern delimiter in the comment--perl has no way of knowing you did not intend to close the pattern early. See the C-comment deletion code in perlop. Also note that anything inside a \Q...\E stays unaffected by /x.

正規表現 Regular Expressions

メタ文字 Metacharacters

Perl のパターンマッチで使われるパターンは Version 8 正規表現 ルーチンで提供されているものからの派生です. (このルーチンは Henry Spencer の自由に再配布可能な V8 ルーチンの再実装から (遠くにはなれつつ)派生しています). 詳細は "Version 8 Regular Expressions" を参照してください. The patterns used in Perl pattern matching evolved from the ones supplied in the Version 8 regex routines. (The routines are derived (distantly) from Henry Spencer's freely redistributable reimplementation of the V8 routines.) See "Version 8 Regular Expressions" for details.

特に以下のメタ文字は標準のegrepっぽい意味を持っています: In particular the following metacharacters have their standard egrep-ish meanings:

    \	Quote the next metacharacter
    ^	Match the beginning of the line
    .	Match any character (except newline)
    $	Match the end of the line (or before newline at the end)
    |	Alternation
    ()	Grouping
    []	Character class
    
    \	次のメタ文字をエスケープ
    ^	行の先頭にマッチ
    .	任意の文字にマッチ(但し改行は除く)
    $	行の終端にマッチ(若しくは終端の改行の前)
    |	代替
    ()	グループ化
    []	文字クラス

デフォルトでは, 文字 "^" は文字列の先頭にのみ, そして文字 "$" は 末尾(若しくは末尾の改行の前)にのみマッチすることを保証し, そして Perl は文字列が1行のみを含んでいるという仮定でいくつかの 最適化を行います. 埋め込まれている改行文字は "^" や "$" とは マッチしません. しかし文字列には複数行が格納されていて, "^" は任意の改行の後(但し改行文字が文字列の最後の文字 だった場合は除く), そして "$" は任意の改行の前で マッチさせたいこともあるでしょう. 小さなオーバーヘッドは ありますが, これはパターンマッチで /m 修飾子を使うことで 行うことができます. (古いプログラムでは <$*> を設定することで これを行っていましたがこれは perl 5.9 では削除されています.) By default, the "^" character is guaranteed to match only the beginning of the string, the "$" character only the end (or before the newline at the end), and Perl does certain optimizations with the assumption that the string contains only one line. Embedded newlines will not be matched by "^" or "$". You may, however, wish to treat a string as a multi-line buffer, such that the "^" will match after any newline within the string (except if the newline is the last character in the string), and "$" will match before any newline. At the cost of a little more overhead, you can do this by using the /m modifier on the pattern match operator. (Older programs did this by setting $*, but this practice has been removed in perl 5.9.)

複数行での利用を簡単にするために, 文字 "." は /s 修飾子を 使って Perl に文字列を1行として処理すると伝えない限り 改行にはマッチしません. To simplify multi-line substitutions, the "." character never matches a newline unless you use the /s modifier, which in effect tells Perl to pretend the string is a single line--even if it isn't.

量指定子 Quantifiers

以下の標準的な量指定子を使えます: The following standard quantifiers are recognized:

    *	   Match 0 or more times
    +	   Match 1 or more times
    ?	   Match 1 or 0 times
    {n}    Match exactly n times
    {n,}   Match at least n times
    {n,m}  Match at least n but not more than m times
    
    *	   0 回以上のマッチ
    +	   1 回以上のマッチ
    ?	   1 回若しくは 0 回のマッチ
    {n}    ちょうど n 回のマッチ
    {n,}   n 回以上のマッチ
    {n,m}  n 回以上 m 回以下のマッチ

(これ以外のコンテキストで波括弧が使われたときには 普通の文字として使われます. また, 下限は省略可能では ありません.) "*" 量指定子は {0,} と, "+" 量指定子は {1,} と, そして "?" 量指定子は {0,1} と等価です. n 及び m は perl をビルドしたときに定義した既定の制限より小さな整数回に 制限されます. これは大抵のプラットフォームでは 32766 回に なっています. 実際の制限は次のようなコードを実行すると 生成されるエラーメッセージで見ることができます: (If a curly bracket occurs in any other context, it is treated as a regular character. In particular, the lower bound is not optional.) The "*" quantifier is equivalent to {0,}, the "+" quantifier to {1,}, and the "?" quantifier to {0,1}. n and m are limited to integral values less than a preset limit defined when perl is built. This is usually 32766 on the most common platforms. The actual limit can be seen in the error message generated by code such as this:

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

デフォルトでは, パターンで行われる量指定は"貪欲"です, つまりそれはパターンの残りの部分が可能な範囲で, (始めた地点から)可能な限り多くを先にあるパターンで マッチさせます. もし最小回数でのマッチを 行いたいのであれば, 量指定子の後ろに "?" を続けます. 意味は変更されずに"貪欲さ"だけを変更できます: By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier with a "?". Note that the meanings don't change, just the "greediness":

    *?     Match 0 or more times, not greedily
    +?     Match 1 or more times, not greedily
    ??     Match 0 or 1 time, not greedily
    {n}?   Match exactly n times, not greedily
    {n,}?  Match at least n times, not greedily
    {n,m}? Match at least n but not more than m times, not greedily
    
    *?     0 回以上の貪欲でないマッチ
    +?     1 回以上の貪欲でないマッチ
    ??     0 回若しくは 1 回の貪欲でないマッチ
    {n}?   ちょうど n 回の貪欲でないマッチ
    {n,}?  n 回以上の貪欲でないマッチ
    {n,m}? n 回以上 m 回以下の貪欲でないマッチ

デフォルトでは, パターンのうちの量指定された一部 によってパターン全体がマッチに失敗したとき, Perl はバックトラックを行います. しかしこの 振る舞いは望まれないこともあります. その為 Perl は"強欲な(possessive)"量指定形式も 提供しています. By default, when a quantified subpattern does not allow the rest of the overall pattern to match, Perl will backtrack. However, this behaviour is sometimes undesirable. Thus Perl provides the "possessive" quantifier form as well.

    *+     Match 0 or more times and give nothing back
    ++     Match 1 or more times and give nothing back
    ?+     Match 0 or 1 time and give nothing back
    {n}+   Match exactly n times and give nothing back (redundant)
    {n,}+  Match at least n times and give nothing back
    {n,m}+ Match at least n but not more than m times and give nothing back
    
    *+     0 回以上のマッチでなおかつ全く戻らない
    ++     1 回以上のマッチでなおかつ全く戻らない
    ?+     0 回若しくは 1 回のマッチでなおかつ全く戻らない
    {n}+   ちょうど n 回のマッチでなおかつ全く戻らない (冗長)
    {n,}+  n 回以上のマッチでなおかつ全く戻らない
    {n,m}+ n 回以上 m 回以下のマッチでなおかつ全く戻らない

例えば, For instance,

   'aaaa' =~ /a++a/

は, a++ が文字列中の全ての a を飲み込んで しまい後に何も残さないためマッチしません. この機能は バックトラックするべきでない場所のヒントを perl に 与えるのに非常に便利です. 例えば, 典型的な "ダブルクオート文字列のマッチ"問題で次のように 書くととても効率的になります: will never match, as the a++ will gobble up all the a's in the string and won't leave any for the remaining part of the pattern. This feature can be extremely useful to give perl hints about where it shouldn't backtrack. For instance, the typical "match a double-quoted string" problem can be most efficiently performed when written as:

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

見ての通り最後のクオートがマッチしなかったとき, バックトラックは役に立ちません. 詳細は独立した サブパターン (?>...) を参照してください; 強欲な量指定子はまさにその構文糖です. 例えば この例は次のようにも書けます: as we know that if the final quote does not match, backtracking will not help. See the independent subexpression (?>...) for more details; possessive quantifiers are just syntactic sugar for that construct. For instance the above example could also be written as follows:

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

エスケープシーケンス Escape sequences

パターンはダブルクオート文字列として処理されるため, 以下のエスケープ文字も動作します: Because patterns are processed as double quoted strings, the following also work:

    \t		tab                   (HT, TAB)
    \n		newline               (LF, NL)
    \r		return                (CR)
    \f		form feed             (FF)
    \a		alarm (bell)          (BEL)
    \e		escape (think troff)  (ESC)
    \033	octal char            (example: ESC)
    \x1B	hex char              (example: ESC)
    \x{263a}	wide hex char         (example: Unicode SMILEY)
    \cK		control char          (example: VT)
    \N{name}	named char
    \l		lowercase next char (think vi)
    \u		uppercase next char (think vi)
    \L		lowercase till \E (think vi)
    \U		uppercase till \E (think vi)
    \E		end case modification (think vi)
    \Q		quote (disable) pattern metacharacters till \E
    
    \t		タブ                  (水平タブ;HT, TAB)
    \n		改行                  (LF, NL)
    \r		復帰                  (CR)
    \f		フォームフィード      (FF)
    \a		アラーム (ベル)       (BEL)
    \e		エスケープ (troff 的) (ESC)
    \033	8進文字               (例: ESC)
    \x1B	16進文字              (例: ESC)
    \x{263a}	ワイド16進文字        (例: Unicode SMILEY)
    \cK		制御文字              (例: VT)
    \N{name}	名前付き文字
    \l		次の文字を小文字に (vi 的)
    \u		次の文字を大文字に (vi 的)
    \L		\E まで小文字に (vi 的)
    \U		\E まで大文字に (vi 的)
    \E		変更の終端 (vi 的)
    \Q		\E までパターンメタ文字の無効化(Quote)

use locale の影響下であれば, \l, \L, \u, \U による大文字小文字変換は現在のロケールで処理されます. perllocale を参照してください. \N{name} に関するドキュメントは charnames を参照してください. If use locale is in effect, the case map used by \l, \L, \u and \U is taken from the current locale. See perllocale. For documentation of \N{name}, see charnames.

\Q シーケンス内であっても $ 及び @ のリテラルは 含めることはできません. エスケープされていない $ 及び @ は対応する変数の埋め込みとなり, とはいえエスケープは リテラル文字列 \$ とのマッチになります. m/\Quser\E\@\Qhost/ といった感じに記述する必要があります. You cannot include a literal $ or @ within a \Q sequence. An unescaped $ or @ interpolates the corresponding variable, while escaping will cause the literal string \$ to be matched. You'll need to write something like m/\Quser\E\@\Qhost/.

文字クラス及び他の特殊なエスケープ Character Classes and other Special Escapes

加えて, Perl は以下のものを定義しています: In addition, Perl defines the following:

    \w	     Match a "word" character (alphanumeric plus "_")
    \W	     Match a non-"word" character
    \s	     Match a whitespace character
    \S	     Match a non-whitespace character
    \d	     Match a digit character
    \D	     Match a non-digit character
    \pP	     Match P, named property.  Use \p{Prop} for longer names.
    \PP	     Match non-P
    \X	     Match eXtended Unicode "combining character sequence",
             equivalent to (?:\PM\pM*)
    \C	     Match a single C char (octet) even under Unicode.
	     NOTE: breaks up characters into their UTF-8 bytes,
	     so you may end up with malformed pieces of UTF-8.
	     Unsupported in lookbehind.
    \1       Backreference to a specific group.
	     '1' may actually be any positive integer.
    \g1      Backreference to a specific or previous group,
    \g{-1}   number may be negative indicating a previous buffer and may
             optionally be wrapped in curly brackets for safer parsing.
    \g{name} Named backreference
    \k<name> Named backreference
    \N{name} Named Unicode character, or Unicode escape
    \x12     Hexadecimal escape sequence
    \x{1234} Long hexadecimal escape sequence
    \K       Keep the stuff left of the \K, don't include it in $&
    \v       Vertical whitespace
    \V       Not vertical whitespace
    \h       Horizontal whitespace
    \H       Not horizontal whitespace
    \R       Linebreak
    
    \w	     "単語" 文字にマッチ (英数字及び"_")
    \W	     非"単語"文字にマッチ
    \s	     白空白文字にマッチ
    \S	     非白空白文字にマッチ
    \d	     数字にマッチ
    \D	     非数字にマッチ
    \pP	     名前属性 P にマッチ. 長い名前であれば \p{Prop}.
    \PP	     P以外にマッチ
    \X	     拡張 Unicode "複合文字シーケンス (combining character sequence)"
             のマッチ, (?:\PM\pM*)と等価
    \C	     1つの C 文字 (8進数)にマッチ, Unicode 環境でも同じ.
	     補足: 文字をUTF-8バイト列へと変換するので, 壊れた
	     UTF-8 片となるかもしれません. lookbehind はサポートしていません. 
    \1       指定したグループへの後方参照.
	     '1' には正の整数を指定できます. 
    \g1      指定した若しくは前のグループへの後方参照,
    \g{-1}   数値は前のバッファを示す負の値にもできます, また
             任意で安全にパースするために波括弧で括ることもできます.
    \g{name} 名前指定の後方参照.
    \k<name> 名前指定の後方参照.
    \N{name} 名前指定の Unicode 文字, 若しくは Unicode エスケープ.
    \x12     16進エスケープシーケンス.
    \x{1234} 長い16進エスケープシーケンス.
    \K       \K の左にある物を保持, $& に含めない.
    \v       垂直白空白.
    \V       垂直白空白以外.
    \h       水平白空白.
    \H       水平白空白以外.
    \R       行区切り.

\w は単語全体ではなく, 1つの英数字(アルファベット 若しくは数字)若しくは _ にマッチします. Perl で識別子 となる文字列(これは英単語とは異なります)にマッチさせるためには \w+ を使います. use locale の影響下であれば, \w で適用されるアルファベットは現在のロケールから 採用されます. perllocale を参照してください. \w, \W, \s, \S, \d, そして \D は文字クラスでも 利用できますが, 範囲の両端には使えません. その前後に "-" を 使ったとき, その "-" はリテラルとして処理されます. もし Unicode 環境下であれば \s は "\x{85}", "\x{2028}", そして "\x{2029}" にもマッチします. \pP, \PP, 及び \X の 詳細と独自の \p 及び \P 属性を定義することに関しては perlunicode を, そして Unicode 一般に関しては perluniintro を参照してください. A \w matches a single alphanumeric character (an alphabetic character, or a decimal digit) or _, not a whole word. Use \w+ to match a string of Perl-identifier characters (which isn't the same as matching an English word). If use locale is in effect, the list of alphabetic characters generated by \w is taken from the current locale. See perllocale. You may use \w, \W, \s, \S, \d, and \D within character classes, but they aren't usable as either end of a range. If any of them precedes or follows a "-", the "-" is understood literally. If Unicode is in effect, \s matches also "\x{85}", "\x{2028}", and "\x{2029}". See perlunicode for more details about \pP, \PP, \X and the possibility of defining your own \p and \P properties, and perluniintro about Unicode in general.

\R はネットワーク行末 "\x0D\x0A" を含めた 行区切りにアトミックにマッチします. 本質的に, \R は次と等価です. \R will atomically match a linebreak, including the network line-ending "\x0D\x0A". Specifically, \R is exactly equivelent to

  (?>\x0D\x0A?|[\x0A-\x0C\x85\x{2028}\x{2029}])

補足: \R は文字クラスでは特別な意味を持ちません; 代わりに \v (垂直白空白)を利用してください). Note: \R has no special meaning inside of a character class; use \v instead (vertical whitespace).

POSIX 文字クラス構文 The POSIX character class syntax

    [:class:]

も利用可能です. [ 及び ] ブラケットは リテラルという点に注意してください; これらは 文字クラス式の中で常に使う必要があります. is also available. Note that the [ and ] brackets are literal; they must always be used within a character class expression.

    # this is correct:
    $string =~ /[[:alpha:]]/;

    # this is not, and will generate a warning:
    $string =~ /[:alpha:]/;

利用可能な文字クラスとそれと等価な バックスラッシュ記法(提供されていれば)は以下の通りです: The available classes and their backslash equivalents (if available) are as follows:

    alpha
    alnum
    ascii
    blank		[1]
    cntrl
    digit       \d
    graph
    lower
    print
    punct
    space       \s	[2]
    upper
    word        \w	[3]
    xdigit
[1]

[ \t] と等価な GNU 拡張, "全ての水平白空白". A GNU extension equivalent to [ \t], "all horizontal whitespace".

[2]

[[:space:]] には(とても稀な)"垂直タブ", "\cK" 若しくは ASCII での chr(11) が含まれるため \s と完全な等価ではありません. Not exactly equivalent to \s since the [[:space:]] includes also the (very rare) "vertical tabulator", "\cK" or chr(11) in ASCII.

[3]

Perl 拡張, 既出. A Perl extension, see above.

例えば全ての大文字にマッチさせるためには [:upper:] を 使うことができます. [][::] 構成子の一部であって, 完全な文字クラスの一部ではありません. 例えば: For example use [:upper:] to match all the uppercase characters. Note that the [] are part of the [::] construct, not part of the whole character class. For example:

    [01[:alpha:]%]

は, 0, 1, 任意の英字, そしてパーセント記号にマッチします. matches zero, one, any alphabetic character, and the percent sign.

以下の Unicode \p{} 構成子及び等価なバックスラッシュ 文字クラス(提供されていれば)の等式: The following equivalences to Unicode \p{} constructs and equivalent backslash character classes (if available), will hold:

    [[:...:]]	\p{...}		backslash

    alpha       IsAlpha
    alnum       IsAlnum
    ascii       IsASCII
    blank
    cntrl       IsCntrl
    digit       IsDigit        \d
    graph       IsGraph
    lower       IsLower
    print       IsPrint
    punct       IsPunct
    space       IsSpace
                IsSpacePerl    \s
    upper       IsUpper
    word        IsWord
    xdigit      IsXDigit

例えば [[:lower:]]\p{IsLower} は等価です. For example [[:lower:]] and \p{IsLower} are equivalent.

utf8 プラグマは使われていなくて locale プラグマが 使われていた場合にはクラスは通常の isalpha(3) インターフェースと 相互に関連します(但し "word" 及び "blank" は除く). If the utf8 pragma is not used but the locale pragma is, the classes correlate with the usual isalpha(3) interface (except for "word" and "blank").

明確ではない名前付き文字は以下の通りです: The assumedly non-obviously named classes are:

cntrl

任意の制御文字. 通常出力を生成する代わりにターミナルの制御を 行う文字: 例えば改行やバックスペースは制御文字です. ord() が32未満となる全ての文字は制御文字として 分類され(ASCII, ISO ラテン文字集合, 及び Unicodeを仮定), ord() が値 127 となる文字(DEL)も同様です. Any control character. Usually characters that don't produce output as such but instead control the terminal somehow: for example newline and backspace are control characters. All characters with ord() less than 32 are usually classified as control characters (assuming ASCII, the ISO Latin character sets, and Unicode), as is the character with the ord() value of 127 (DEL).

graph

全ての英数字及び句読点(特殊)文字. Any alphanumeric or punctuation (special) character.

print

全ての英数字, 句読点(特殊)文字, 及び空白文字. Any alphanumeric or punctuation (special) character or the space character.

punct

全ての句読点(特殊)文字. Any punctuation (special) character.

xdigit

全ての16進数字. これはいまひとつぽいけれど([0-9A-Fa-f]も ちゃんと動作します), 完全性のために含まれています. Any hexadecimal digit. Though this may feel silly ([0-9A-Fa-f] would work just fine) it is included for completeness.

クラス名の前に '^' をおくことで [::] 文字クラスの 補集合を使うこともできます. これは Perl での拡張です. 例: You can negate the [::] character classes by prefixing the class name with a '^'. This is a Perl extension. For example:

    POSIX         traditional  Unicode
    POSIX         普段の       Unicode

    [[:^digit:]]    \D         \P{IsDigit}
    [[:^space:]]    \S         \P{IsSpace}
    [[:^word:]]	    \W         \P{IsWord}

Perl は POSIX 文字クラスにある POSIX 標準は 文字クラスのみをサポートしていると考えます. POSIX 文字クラス [.cc.] 及び [=cc=] は認識されますが, サポートはされておらずそれを使うとエラーとなるでしょう. Perl respects the POSIX standard in that POSIX character classes are only supported within a character class. The POSIX character classes [.cc.] and [=cc=] are recognized but not supported and trying to use them will cause an error.

アサーション(言明) Assertions

Perl は以下のゼロ幅のアサーションを定義しています: Perl defines the following zero-width assertions:

    \b	Match a word boundary
    \B	Match except at a word boundary
    \A	Match only at beginning of string
    \Z	Match only at end of string, or before newline at the end
    \z	Match only at end of string
    \G	Match only at pos() (e.g. at the end-of-match position
        of prior m//g)
    
    \b	単語境界にマッチ
    \B	単語境界以外にマッチ
    \A	文字列の開始にのみマッチ
    \Z	文字列の終端若しくは終端の改行前にのみマッチ
    \z	文字列の終端にのみマッチ
    \G	pos() の位置にのみマッチ (つまり前のm//gのマッチ終端位置)

単語境界(\b)は\W にマッチする文字列の始まりと 終わりを連想するような, 片側を \w, もう片側を \W で挟まれている点です. (文字クラスにおいては \b は単語境界ではなくバックスペースを表します, ちょうどダブルクオート文字列と同じように.) \A 及び \Z は "^" 及び "$" と同様ですが, /m 修飾子が指定されているときに "^" 及び "$" は全ての内部的な行境界にマッチするのに対して \A 及び \Z は複数回のマッチにはなりません. 文字列の本当の末尾にマッチさせ, 省略可能である 末尾の改行を無視しないようにする \z を使います. A word boundary (\b) is a spot between two characters that has a \w on one side of it and a \W on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a \W. (Within character classes \b represents backspace rather than a word boundary, just as it normally does in any double-quoted string.) The \A and \Z are just like "^" and "$", except that they won't match multiple times when the /m modifier is used, while "^" and "$" will match at every internal line boundary. To match the actual end of the string and not ignore an optional trailing newline, use \z.

\G アサーションはグローバルなマッチ(m//g)を 連結するために使います, これは perlop 内 "Regexp Quote-Like Operators" にも説明されて います. これは文字列に対していくつかのパターンを 次々にマッチさせたいといった, lex ライクなスキャナを 書きたいときにも便利です, 同じリファレンスを参照してください. \G が実際にマッチできる位置は pos() を左辺値として 使うことで変更できます: perlfunc 内 "pos" を参照してください. ゼロ幅マッチのルールは少し変化することに注意してください, \G の左にある内容はマッチの長さを決定するときに 数えられません. 従って次のコードは永遠にマッチしません: The \G assertion can be used to chain global matches (using m//g), as described in "Regexp Quote-Like Operators" in perlop. It is also useful when writing lex-like scanners, when you have several patterns that you want to match against consequent substrings of your string, see the previous reference. The actual location where \G will match can also be influenced by using pos() as an lvalue: see "pos" in perlfunc. Note that the rule for zero-length matches is modified somewhat, in that contents to the left of \G is not counted when determining the length of the match. Thus the following will not match forever:

    $str = 'ABC';
    pos($str) = 1;
    while (/.\G/g) {
        print $&;
    }

これはゼロ幅へのマッチと見なされ, 'A' を出力し終了します, そして行の中で同じ場所に二度はマッチしません. It will print 'A' and then terminate, as it considers the match to be zero-width, and thus will not match at the same position twice in a row.

適切に使われていない \G は無限ループとなり 何の価値もありません. 代替(alternation; |)の中に \G を含んでいるパターンを使う際には十分注意してください. It is worth noting that \G improperly used can result in an infinite loop. Take care when using patterns that include \G in an alternation.

キャプチャバッファ Capture buffers

( ... ) を構成するブラケットはキャプチャバッファを 生成します. 同じパターンの後方で内容を参照するには, 最初のものであれば \1 を, 2番目の物であれば \2 を使います. マッチの外側では "\" の代わりに "$" を使います. (\<数字> 記法はマッチの外側でも特定の状況では動作します. \1 と $1 に関する警告の詳細は後述を参照してください.) マッチの別の部分を戻って参照することは, 後方参照 (backreference)と呼ばれます. The bracketing construct ( ... ) creates capture buffers. To refer to the current contents of a buffer later on, within the same pattern, use \1 for the first, \2 for the second, and so on. Outside the match use "$" instead of "\". (The \<digit> notation works in certain circumstances outside the match. See the warning below about \1 vs $1 for details.) Referring back to another part of the match is called a backreference.

使用できるキャプチャされた部分文字列の数に制限はありません. しかし Perl は \10, \11, etc. を \010, \011, etc. の エイリアスとして使います. (0 は8進数を意味することを 思い出してください, つまり \011 はあなたのコーディング している文字集合での番号 9 にあたる文字になります; これは10番目の文字であり, ASCII においては水平タブに なります.) Perl はこれを両方の意味で解釈し, 少なくとも 10 の左括弧が使われていれば \10 を後方参照として解釈します. 同じように 11 の左括弧があれば \11 を後方参照として 解釈します. その先も同様です. \1 から \9 は常に後方参照 として解釈されます. There is no limit to the number of captured substrings that you may use. However Perl also uses \10, \11, etc. as aliases for \010, \011, etc. (Recall that 0 means octal, so \011 is the character at number 9 in your coded character set; which would be the 10th character, a horizontal tab under ASCII.) Perl resolves this ambiguity by interpreting \10 as a backreference only if at least 10 left parentheses have opened before it. Likewise \11 is a backreference only if at least 11 left parentheses have opened before it. And so on. \1 through \9 are always interpreted as backreferences.

後方参照を使ったパターンをより安全で簡単に構成するために, Perl 5.10 は \g{N} 記法を提供します. 波括弧は任意ですが, 省略するとそれに続くテキストが変わると(つまり数字が続く場合に) 安全ではなくなります. N が正の整数のとき, \g{N} は 通常の後方参照と丁度同じです. N が負の整数の時, N 個前のキャプチャグループを参照する相対的な後方参照 になります. ブラケット形式で N が整数でないときは 名前付きバッファへの参照として扱われます. In order to provide a safer and easier way to construct patterns using backreferences, Perl 5.10 provides the \g{N} notation. The curly brackets are optional, however omitting them is less safe as the meaning of the pattern can be changed by text (such as digits) following it. When N is a positive integer the \g{N} notation is exactly equivalent to using normal backreferences. When N is a negative integer then it is a relative backreference referring to the previous N'th capturing group. When the bracket form is used and N is not an integer, it is treated as a reference to a named buffer.

従って \g{-1} は最後のバッファを, \g{-2} は その前のバッファを参照します. 例えば: Thus \g{-1} refers to the last buffer, \g{-2} refers to the buffer before that. For example:

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

/(Y) ( (X) \3 \1 )/x と同じマッチとなります. and would match the same as /(Y) ( (X) \3 \1 )/x.

加えて, 5.10 時点では名前付きキャプチャバッファ 及び名前付き後方参照を利用できます. (?<name>...) で宣言し, \k<name> で参照します. 名前区切りに各括弧の代わりにアポストロフィを使うこともできます; そしてブラケットによる \g{name} 後方参照構文を 使うこともできます. 名前付きキャプチャバッファを 通常通りに絶対及び相対番号で参照することもできます. パターンの外においては, 名前付きキャプチャバッファは %+ ハッシュを通して利用できます. 同じパターン内で 異なるバッファが同じ名前を持っていたとき, $+{name} 及び \k<name> は一番左で定義されたグループを 参照します. (つまり処理のために C(<??{}))> を必要と する別の方法の名前付きキャプチャバッファで 行うこともできます.) Additionally, as of Perl 5.10 you may use named capture buffers and named backreferences. The notation is (?<name>...) to declare and \k<name> to reference. You may also use apostrophes instead of angle brackets to delimit the name; and you may use the bracketed \g{name} backreference syntax. It's possible to refer to a named capture buffer by absolute and relative number as well. Outside the pattern, a named capture buffer is available via the %+ hash. When different buffers within the same pattern have the same name, $+{name} and \k<name> refer to the leftmost defined group. (Thus it's possible to do things with named capture buffers that would otherwise require (??{}) code to accomplish.)

例: Examples:

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

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

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

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

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

    s/^([^ ]*) *([^ ]*)/$2 $1/;     # 最初の2つの単語を入れ替え.

    /(.)\1/                         # 最初の重複した文字を探索.
         and print "'$1' is the first doubled character\n";

    /(?<char>.)\k<char>/            # ... 違ったやり方で.
         and print "'$+{char}' is the first doubled character\n";

    /(?'char'.)\1/                  # ... ごちゃ混ぜ.
         and print "'$1' is the first doubled character\n";

    if (/Time: (..):(..):(..)/) {   # 値の抽出.
	$hours = $1;
	$minutes = $2;
	$seconds = $3;
    }

いくつかの特殊変数もまた以前のマッチの一部を 参照しています. $+ は最後のマッチした のブラケットマッチと返します. $& はマッチした 文字列全体を返します. (一頃は $0 もそうでしたが, 現在ではこれはプログラム名を返します.) $` はマッチした文字列の前の全てを返します. $' はマッチした文字列の後の全てを返します. そして $^N には一番最後に閉じたグループ(サブマッチ) にマッチしたものを含んでいます. $^N は 例えばサブマッチを変数に格納するため等に 拡張パターンの中でも利用できます(後述). Several special variables also refer back to portions of the previous match. $+ returns whatever the last bracket match matched. $& returns the entire matched string. (At one point $0 did also, but now it returns the name of the program.) $` returns everything before the matched string. $' returns everything after the matched string. And $^N contains whatever was matched by the most-recently closed group (submatch). $^N can be used in extended patterns (see below), for example to assign a submatch to a variable.

数値によるマッチ変数($1, $2, $3, etc.)及び 関連する記号変数($+, $&, $', 及び $^N)はすべて ブロックの終端若しくは次のマッチ成功までのどちらか先に 満たした方の, 動的なスコープを持ちます. (perlsyn 内 "Compound Statements" 参照.) The numbered match variables ($1, $2, $3, etc.) and the related punctuation set ($+, $&, $`, $', and $^N) are all dynamically scoped until the end of the enclosing block or until the next successful match, whichever comes first. (See "Compound Statements" in perlsyn.)

補足: Perl において失敗したマッチは マッチ変数をリセットしません, これはより 特殊化させる一連のテストを書くことや, 最善のマッチを書くとことを容易にします. NOTE: Failed matches in Perl do not reset the match variables, which makes it easier to write code that tests for a series of more specific cases and remembers the best match.

警告: Perl は, 一旦プログラム中のどこかで $&, $`, 若しくは $' のいずれかを必要としていることを見つけると, 全てのパターンマッチでそれらを提供しなければなりません. これはあなたのプログラムを大幅に遅くさせるでしょう. Perl は $1, $2, 等の生成にも同じメカニズムを使っているので, キャプチャの括弧に含まれるそれぞれのパターンにも 同じ料金を払っています. (グループ化の振る舞いを維持しつつ このコストを削減するには拡張正規表現 (?: ... ) を代わりに 使います. (訳注:Perl拡張というだけで /x 修飾子は不要.)) ですが $&, $` 若しくは $' を一度も使わなければ, キャプチャの括弧をもたないパターンではこの不利益は なくなります. この為, 可能であれば $&, $', 及び $` を削除しましょう, しかしそれができなかった(そしてそれらを 本当に理解しているアルゴリズムがあるのであれば), 一旦 それらを使った時点でそれ以降は自由にそれらを使うことができます, なぜならあなたは(一度使った時点で)既に代価を払っているので. 5.005 であれば $& は他の2つほど高価ではありません. WARNING: Once Perl sees that you need one of $&, $`, or $' anywhere in the program, it has to provide them for every pattern match. This may substantially slow your program. Perl uses the same mechanism to produce $1, $2, etc, so you also pay a price for each pattern that contains capturing parentheses. (To avoid this cost while retaining the grouping behaviour, use the extended regular expression (?: ... ) instead.) But if you never use $&, $` or $', then patterns without capturing parentheses will not be penalized. So avoid $&, $', and $` if you can, but if you can't (and some algorithms really appreciate them), once you've used them once, use them at will, because you've already paid the price. As of 5.005, $& is not so costly as the other two.

この問題に対する解決策として, Perl 5.10 からは $`, $& 及び $' と等価だけれども /p (preseve) 修飾子を伴って実行されたマッチが成功した後でのみ 定義されることが保証される ${^PREMATCH}, ${^MATCH} 及び ${^POSTMATCH} を導入しました. これらの変数の使用は利用したいときに perl に伝える 必要がある代わりに, 等価な記号変数とは違い 全体的なパフォーマンスの低下を引き起こしません. As a workaround for this problem, Perl 5.10 introduces ${^PREMATCH}, ${^MATCH} and ${^POSTMATCH}, which are equivalent to $`, $& and $', except that they are only guaranteed to be defined after a successful match that was executed with the /p (preserve) modifier. The use of these variables incurs no global performance penalty, unlike their punctuation char equivalents, however at the trade-off that you have to tell perl when you want to use them.

Perl においてバックスラッシュで表現されるメタ文字は \b, \w, \n のように英数字です. 他の正規表現 言語とは異なり, 英数字でないシンボルのバックスラッシュ はありません. なので \\, \(, \), \<, \>, \{, 若しくは \} といったものは全てメタ文字ではなく リテラル文字です. これはパターンで使いたい文字列の中で 正規表現のメタ文字としての特殊な意味を無効化若しくは クオートするための一般的な指標として使われてきました. "単語"でない全ての文字は単にクオートします: Backslashed metacharacters in Perl are alphanumeric, such as \b, \w, \n. Unlike some other regular expression languages, there are no backslashed symbols that aren't alphanumeric. So anything that looks like \\, \(, \), \<, \>, \{, or \} is always interpreted as a literal character, not a metacharacter. This was once used in a common idiom to disable or quote the special meanings of regular expression metacharacters in a string that you want to use for a pattern. Simply quote all non-"word" characters:

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

(もし use locale が有効であれば, これは現在の ロケールに依存します.) 今日では特殊な意味を持つ メタ文字を全て無効にするためには次のように quotemeta() 関数か \Q メタクオート エスケープシーケンスを使うのがより一般的です: (If use locale is set, then this depends on the current locale.) Today it is more common to use the quotemeta() function or the \Q metaquoting escape sequence to disable all metacharacters' special meanings like this:

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

\Q 及び \E の間でリテラルとしてバックスラッシュを おくとき(埋め込んだ変数の中でではない)には, 二重にクオートしたバックスラッシュの埋め込みは 困惑した結果となるでしょう. もし \Q...\E で リテラルとしてのバックスラッシュを使う必要があるのなら, perlop 内 "Gory details of parsing quoted constructs" を参照してください. Beware that if you put literal backslashes (those not inside interpolated variables) between \Q and \E, double-quotish backslash interpolation may lead to confusing results. If you need to use literal backslashes within \Q...\E, consult "Gory details of parsing quoted constructs" in perlop.

拡張パターン Extended Patterns

Perl は awklex といった標準的なツール では見られない機能のための拡張構文も定義しています. 構文は対の括弧と括弧内の最初に疑問符の形をとります. 疑問符の後の文字で拡張を区別します. Perl also defines a consistent extension syntax for features not found in standard tools like awk and lex. The syntax is a pair of parentheses with a question mark as the first thing within the parentheses. The character after the question mark indicates the extension.

拡張構文の安定度は様々です. 中には長年言語コアの 一部となっている物もあります. そうでなく実験的に 追加され警告なしに変更されたり削除されるものも 中にはあります. それぞれのステータスに関しては 個々の機能のドキュメントを確認してください. The stability of these extensions varies widely. Some have been part of the core language for many years. Others are experimental and may change without warning or be completely removed. Check the documentation on an individual feature to verify its current status.

疑問符は 1) それが古い正規表現で使われることは稀 であること, そして 2) それを見かけると何が行われるのか 本当に"疑問に"思って止まることから, これのためと 最小マッチ構成子のために選ばれました. A question mark was chosen for this and for the minimal-matching construct because 1) question marks are rare in older regular expressions, and 2) whenever you see one, you should stop and "question" exactly what is going on. That's psychology...

(?#text)

コメント. テキストは無視されます. /x 修飾子によって 白空白の整形が有効にされていれば単なる # でも十分です. Perl は ) を見つけると直ぐにコメントを閉じる点に 注意してください, この為リテラル ) をコメント中に おくことはできません. A comment. The text is ignored. If the /x modifier enables whitespace formatting, a simple # will suffice. Note that Perl closes the comment as soon as it sees a ), so there is no way to put a literal ) in the comment.

(?pimsx-imsx)

1つ若しくは複数のパターンマッチ修飾子, パターンの残り若しくは(もしあれば)包含している パターングループののこりで有効にする(若しくは - が 全治されていれば解除する). これは設定ファイルから 読む, 引数から取る, 若しくはどこかのテーブルで 指定されている箇所からダイナミックなパターンを 使うときに特に便利です. パターンの一部では大文字 小文字を区別したいけれども別の箇所では区別しない といったケースを考えてみます: 区別をしない場所では 単にパターンの先頭に (?i) を含めるだけです. 例えば: One or more embedded pattern-match modifiers, to be turned on (or turned off, if preceded by -) for the remainder of the pattern or the remainder of the enclosing pattern group (if any). This is particularly useful for dynamic patterns, such as those read in from a configuration file, taken from an argument, or specified in a table somewhere. Consider the case where some patterns want to be case sensitive and some do not: The case insensitive ones merely need to include (?i) at the front of the pattern. For example:

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

    # more flexible:

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

これらの修飾子は包含しているグループの最後で 復元(restore)されます. 例えば, These modifiers are restored at the end of the enclosing group. For example,

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

blah に大文字小文字の区別なくマッチし, いくつかの空白, そして前の単語その物(大文字小文字の 区別まで含めて!)に再度マッチします, ここではこの グループの外側で /x 修飾子を持ち, /i 修飾子を 持たないものとします. will match blah in any case, some spaces, and an exact (including the case!) repetition of the previous word, assuming the /x modifier, and no /i modifier outside this group.

p 修飾子は有効にできるのみで, 無効にはできない点, そしてパターンのどこかにあればパターン全体で有効になる 点で特別です. 従って (?-p) 及び (?-p:...) は 意味を持たず, use warnings の下では警告を発します. Note that the p modifier is special in that it can only be enabled, not disabled, and that its presence anywhere in a pattern has a global effect. Thus (?-p) and (?-p:...) are meaningless and will warn when executed under use warnings.

(?:pattern)
(?imsx-imsx:pattern)

これはキャプチャではなくクラスタです; これは "()" のように部分式をグループ化しますが "()" が 行うような後方参照は行いません. つまり, This is for clustering, not capturing; it groups subexpressions like "()", but doesn't make backreferences as "()" does. So

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

は次と同様ですが is like

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

余計なフィールドを引き出しません. また不要であれば 文字のキャプチャを行わないため低コストです. but doesn't spit out extra fields. It's also cheaper not to capture characters if you don't need to.

? 及び : の間の文字は (?imsx-imsx) のようなフラグ修飾子として動作します. Any letters between ? and : act as flags modifiers as with (?imsx-imsx). For example,

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

はより冗長に書けば以下と等価です is equivalent to the more verbose

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

これは各代替分岐においてキャプチャバッファを 同じ番号から始める特殊な属性を持っている, "ブランチリセット(branch reset)" パターンです. これは perl 5.10 から提供されています. This is the "branch reset" pattern, which has the special property that the capture buffers are numbered from the same starting point in each alternation branch. It is available starting from perl 5.10.

キャプチャバッファは左から右へと番号が 振られますが, この構成子の内側では各分岐毎に 番号はリセットされます. Capture buffers are numbered from left to right, but inside this construct the numbering is restarted for each branch.

各分岐内での番号図毛は通常通りに行われ, この構成子の後に続くバッファはその中で キャプチャバッファが一番多かった分岐のみが 格納されていたかのように番号付けされていきます. The numbering within each branch will be as normal, and any buffers following this construct will be numbered as though the construct contained only one branch, that being the one with the most capture buffers in it.

この構成子はいくつかの代替マッチの1つをキャプチャ したいときに便利です. This construct will be useful when you want to capture one of a number of alternative matches.

以下のパターンを想像してみてください. 下側の番号は内容の格納されるバッファを示します. Consider the following pattern. The numbers underneath show in which buffer the captured content will be stored.

    # before  ---------------branch-reset----------- after        
    / ( a )  (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x
    # 1            2         2  3        2     3     4
先読み及び後読みの言明 Look-Around Assertions

先読み及び後読みの言明(assertion)は $& の中に 含めない特定のパターンにマッチするゼロ幅のパターンです. 正の言明はその部分パターンがマッチしたときにマッチし, 負の言明はその部分パターンが失敗したときにマッチします. 後読みのマッチは今のマッチ位置までのテキストにマッチし, 先読みの言明は今のマッチ位置の先にあるテキストにマッチします. Look-around assertions are zero width patterns which match a specific pattern without including it in $&. Positive assertions match when their subpattern matches, negative assertions match when their subpattern fails. Look-behind matches text up to the current match position, look-ahead matches text following the current match position.

 訳注:
   後読み, 先読みはマッチの進む方向に対して.
     m{ (?<=abc)       def     (?=ghi ) }x;
        Look-behind -> body -> Look-ahead.
        後読み      -> 本体 -> 先読み
(?=pattern)

ゼロ幅の正の先読み言明. 例えば, /\w+(?=\t)/ は タブが続く単語にマッチしますが, タブは $& に 含まれません. A zero-width positive look-ahead assertion. For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab in $&.

(?!pattern)

ゼロ幅の負の先読み言明. 例えば /foo(?!bar)/ は "bar" が続かない全ての "foo" にマッチします. しかしながら先読みと後読みは同じ物では ない 点に 注意してください. これを後読みに使うことはできません. A zero-width negative look-ahead assertion. For example /foo(?!bar)/ matches any occurrence of "foo" that isn't followed by "bar". Note however that look-ahead and look-behind are NOT the same thing. You cannot use this for look-behind.

もし "foo" が前にない "bar" を探しているのなら, /(?!foo)bar/ では欲しい物にはなりません. なぜなら (?!foo) は 次のものが "foo" ではないとだけいっているのです -- そしてそうではなく, そこには "bar" があるので, "foobar" はマッチします. このような時には /(?!foo)...bar/ のような形で使う必要があるでしょう. ここで "ような" と いっているのは "bar" が場合によっては3文字ではないことも あるからです. 次のようにしてこれをカバーすることが できます: /(?:(?!foo)...|^.{0,2})bar/. またもっと簡単に次のようにできることもあるでしょう: If you are looking for a "bar" that isn't preceded by a "foo", /(?!foo)bar/ will not do what you want. That's because the (?!foo) is just saying that the next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" will match. You would have to do something like /(?!foo)...bar/ for that. We say "like" because there's the case of your "bar" not having three characters before it. You could cover that this way: /(?:(?!foo)...|^.{0,2})bar/. Sometimes it's still easier just to say:

    if (/bar/ && $` !~ /foo$/)

後読みは以下を参照. For look-behind see below.

(?<=pattern) \K

ゼロ幅の正の後読みの言明. 例えば, /(?<=\t)\w+/ は タブに続く単語にマッチしますが, タブは $& に 含まれません. 固定幅の後読みのみが動作します. A zero-width positive look-behind assertion. For example, /(?<=\t)\w+/ matches a word that follows a tab, without including the tab in $&. Works only for fixed-width look-behind.

\K というこの構成子の特殊な形式もあります, これは正規表現エンジンに対してそれが \K までに マッチしたすべてのものを"取っておいて", $& には 含めないようにさせます. これは事実上可変長の後読みを 提供します. 他の先読み及び後読みの言明の中での利用も 可能ですが, その振る舞いは今のところあまり定義されて いません. There is a special form of this construct, called \K, which causes the regex engine to "keep" everything it had matched prior to the \K and not include it in $&. This effectively provides variable length look-behind. The use of \K inside of another look-around assertion is allowed, but the behaviour is currently not well defined.

いくつかの理由から, \K は等価な (?<=...) 構成子より非常に効率的で, 文字列の中で何かに続いている 何かを効率的に取り除きたいようなシチュエーションで 効果的に役立ちます. 例えば For various reasons \K may be significantly more efficient than the equivalent (?<=...) construct, and it is especially useful in situations where you want to efficiently remove something following something else in a string. For instance

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

次のようにより効率的に書き直せます can be rewritten as the much more efficient

  s/foo\Kbar//g;
(?<!pattern)

ゼロ幅の負の後読みの言明. 例えば /(?<!bar)foo/ は "bar" に続いていない任意の "foo" にマッチします. 固定幅の後読みのみが動作します. A zero-width negative look-behind assertion. For example /(?<!bar)foo/ matches any occurrence of "foo" that does not follow "bar". Works only for fixed-width look-behind.

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

名前付のキャプチャバッファ. 通常のキャプチャ括弧 () と同様ですがそれに加えて 成功したマッチの後で名前付バッファを参照するために %+ を 使うことが出来ます. %+ ハッシュに関する詳細は perlvar を 参照してください. A named capture buffer. Identical in every respect to normal capturing parentheses () but for the additional fact that %+ may be used after a successful match to refer to a named buffer. See perlvar for more details on the %+ hash.

複数の異なるキャプチャバッファが同じ名前を持っていたときには $+{NAME} はマッチの中で一番左で定義されたバッファを参照します. If multiple distinct capture buffers have the same name then the $+{NAME} will refer to the leftmost defined buffer in the match.

2つの形式 (?'NAME'pattern) 及び (?<NAME>pattern) は 等価です. The forms (?'NAME'pattern) and (?<NAME>pattern) are equivalent.

補足: これを構成する記法は 類似していている .NET での正規表現と同じですが, 振る舞いは異なります. Perl ではバッファは名前がついているかどうかに かかわらず順番に番号が振られます. 従って 次のパターンにおいて NOTE: While the notation of this construct is the same as the similar function in .NET regexes, the behavior is not. In Perl the buffers are numbered sequentially regardless of being named or not. Thus in the pattern

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

$+{foo} は $2 と同じであり, $3 には .NET 正規表現に なれた人が予測するのとはことなり 'z' が含まれます. $+{foo} will be the same as $2, and $3 will contain 'z' instead of the opposite which is what a .NET regex hacker might expect.

現在のところ NAME はシンプルな識別子のみに制限されて います. 言い換えると, /^[_A-Za-z][_A-Za-z0-9]*\z/ 若しくはその Unicode 拡張にマッチしなければなりません (utf8 も参照), しかしロケールでは拡張されません (perllocale 参照). Currently NAME is restricted to simple identifiers only. In other words, it must match /^[_A-Za-z][_A-Za-z0-9]*\z/ or its Unicode extension (see utf8), though it isn't extended by the locale (see perllocale).

補足: Python や PCRE 正規表現エンジンになれたプログラマが 楽になるように, (?<NAME>pattern) の代わりに (?P<NAME>pattern) のパターンを使うことも できます; しかしこの形式は名前のデリミタとして シングルクオートの使用はサポートされていません. これは Perl 5.10 以降で提供されています. NOTE: In order to make things easier for programmers with experience with the Python or PCRE regex engines, the pattern (?P<NAME>pattern) may be used instead of (?<NAME>pattern); however this form does not support the use of single quotes as a delimiter for the name. This is only available in Perl 5.10 or later.

\k<NAME>
\k'NAME'

名前による後方参照. 数値によってではなく名前によって グループを指定する点を除いて, 名前による後方参照とにています. もし同じ名前の複数のグループがあったときには現在のマッチで 一番左に定義されているグループを参照します. Named backreference. Similar to numeric backreferences, except that the group is designated by name and not number. If multiple groups have the same name then it refers to the leftmost defined group in the current match.

パターン内で (?<NAME>) によって定義されていない名前を 参照するとエラーになります. It is an error to refer to a name not defined by a (?<NAME>) earlier in the pattern.

両方の形式とも等価です. Both forms are equivalent.

補足: Python や PCRE 正規表現エンジンになれたプログラマが 楽になるように, Perl 5.10 以降では \k<NAME> の代わりに (?P=NAME) のパターンを使うことも できます. NOTE: In order to make things easier for programmers with experience with the Python or PCRE regex engines, the pattern (?P=NAME) may be used instead of \k<NAME> in Perl 5.10 or later.

(?{ code })

警告: この拡張正規表現の機能は実験的なものと考えてください, また追う通知なしに変更されるかもしれません. 副作用を持つコードの実行は今後の正規表現エンジンの 最適化の影響でバージョン間で必ずしも同じになるとは 限らないでしょう. WARNING: This extended regular expression feature is considered experimental, and may be changed without notice. Code executed that has side effects may not perform identically from version to version due to the effect of future optimisations in the regex engine.

このゼロ幅アサーションは埋め込まれた任意の Perl コードを評価します. これは常に(正規表現として)成功し, その code は埋め込まれません. 今のところ, code が終わる場所を認識するルールは少々複雑です. This zero-width assertion evaluates any embedded Perl code. It always succeeds, and its code is not interpolated. Currently, the rules to determine where the code ends are somewhat convoluted.

この機能では一緒にネストした括弧の数を数えなくとも1つ前の マッチ結果をキャプチャ特殊変数 $^N を使うことができます. This feature can be used together with the special variable $^N to capture the results of submatches in variables without having to keep track of the number of nested parentheses. For example:

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

(?{...}) ブロックの中では $_ は正規表現をマッチさせている文字列を 参照します. pos() を使ってこの文字列で現在のマッチ位置を知ることも できます. Inside the (?{...}) block, $_ refers to the string the regular expression is matching against. You can also use pos() to know what is the current position of matching within this string.

code は次の感じで適切にスコープを持ちます: もしアサーションが バックトラックされている("バックトラック" 参照)のなら, local されなかった後の全ての変更, つまり The code is properly scoped in the following sense: If the assertion is backtracked (compare "Backtracking"), all changes introduced after localization are undone, so that

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

$res = 4 を設定します. マッチの後で $cnt はグローバルに設定された値を 返します, なぜなら local 演算子で制限されたスコープは巻き戻されるためです. will set $res = 4. Note that after the match, $cnt returns to the globally introduced value, because the scopes that restrict local operators are unwound.

このアサーションは (?(condition)yes-pattern|no-pattern) スイッチ として使われるかもしれません. この方法で使われなかったのなら, code の評価結果は特殊変数 $^R におかれます. これはすぐに 行われるので $^R は同じ正規表現内の他の $?{ code }) アサーションで使うことができます. This assertion may be used as a (?(condition)yes-pattern|no-pattern) switch. If not used in this way, the result of evaluation of code is put into the special variable $^R. This happens immediately, so $^R can be used from other (?{ code }) assertions inside the same regular expression.

この $^R への設定は適切にlocal化されるため, $^R の古い 値はバックトラックしたときには復元されます; "バックトラック" を見てください. The assignment to $^R above is properly localized, so the old value of $^R is restored if the assertion is backtracked; compare "Backtracking".

不運にも実装上の理由によりこれらのブロックに含まれる Perl コードは 関数やループ内でレキシカルスコープな変数とともに使うと 一見奇妙な結果を持つコンパイル時のクロージャとして 扱われます. これの対処方法は, 単純にに代わりにグローバル変数を 使うことも含めて幾つかあります. もしこの構成子を使って奇妙な結果が 発生しているのなら, レキシカルスコープな変数を使っているかどうかを 確認してみてください. Due to an unfortunate implementation issue, the Perl code contained in these blocks is treated as a compile time closure that can have seemingly bizarre consequences when used with lexically scoped variables inside of subroutines or loops. There are various workarounds for this, including simply using global variables instead. If you are using this construct and strange results occur then check for the use of lexically scoped variables.

セキュリティ的な理由により, 正規表現を実行時に変数から構築する ことは, 危険な use re 'eval' プラグマが使われている(re参照)か 変数が qr// 演算子(perlop 内 "qr/STRING/imosx"参照)の結果を 含んでいる時以外は拒否されます. For reasons of security, this construct is forbidden if the regular expression involves run-time interpolation of variables, unless the perilous use re 'eval' pragma has been used (see re), or the variables contain results of qr// operator (see "qr/STRING/imosx" in perlop).

この制限は, 実行時に決まる文字列をパターンとして使う, とても広まっていてとても便利な風習のためのものです. 例えば: This restriction is due to the wide-spread and remarkably convenient custom of using run-time determined strings as patterns. For example:

    $re = <>;
    chomp $re;
    $string =~ /$re/;

Perl がパターンの中にあるコードを実行する方法を知る前は この操作は不正なパターンで例外を発生させはしますが セキュリティ的な視点で完全に安全でした. もし use re 'eval' を有効にしている のなら, これはもはやセキュアではありません, そして taint チェックを 使っているときにだけ行うべきです. より良い方法としては, Safe の区画内で注意深く制限された評価を使うべきでしょう. この 双方のメカニズムについての詳細は perlsec を参照してください. Before Perl knew how to execute interpolated code within a pattern, this operation was completely safe from a security point of view, although it could raise an exception from an illegal pattern. If you turn on the use re 'eval', though, it is no longer secure, so you should only do so if you are also using taint checking. Better yet, use the carefully constrained evaluation within a Safe compartment. See perlsec for details about both these mechanisms.

Perl の正規表現エンジンは今のところリエントラントではないので, 埋め込まれたコードからは m// 若しくは s/// を使って直接 的にでも split のような関数を使って間接的にでも呼び出さないで ください. Because Perl's regex engine is currently not re-entrant, interpolated code may not invoke the regex engine either directly with m// or s///), or indirectly with functions such as split.

(??{ code })

警告: この拡張正規表現の機能は実験的なものと考えてください, また追う通知なしに変更されるかもしれません. 副作用を持つコードの実行は今後の正規表現エンジンの 最適化の影響でバージョン間で必ずしも同じになるとは 限らないでしょう. WARNING: This extended regular expression feature is considered experimental, and may be changed without notice. Code executed that has side effects may not perform identically from version to version due to the effect of future optimisations in the regex engine.

これは"先送りされた"正規部分表現です. code は実行時に評価され, そのときにこの部分表現にマッチさせます. 評価の結果は正規表現として 受け取られ, この構成子の代わりに入れられていたかのようにマッチ されます. これは eval されたパターン内部で定義されたキャプチャ バッファの内容はパターンの外側では提供されず, そしてその逆も 同様になる点に注意してください, 内側のパターンが外側で定義された キャプチャバッファを参照する方法はありません. 例えば, This is a "postponed" regular subexpression. The code is evaluated at run time, at the moment this subexpression may match. The result of evaluation is considered as a regular expression and matched as if it were inserted instead of this construct. Note that this means that the contents of capture buffers defined inside an eval'ed pattern are not available outside of the pattern, and vice versa, there is no way for the inner pattern to refer to a capture buffer defined outside. Thus,

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

これはマッチ しますが, $1 は設定され ません. will match, it will not set $1.

code は埋め込まれません. 先の時と同様に code が終了していると 決定するルールは少々複雑です. The code is not interpolated. As before, the rules to determine where the code ends are currently somewhat convoluted.

次のパターンは括弧で囲まれたグループにマッチします: The following pattern matches a parenthesized group:

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

同じタスクを行う別の, より効率的な方法として (?PARNO) も 参照してください. See also (?PARNO) for a different, more efficient way to accomplish the same task.

Perl の正規表現エンジンは今のところリエントラントではないので, 遅延されたコードからは m// 若しくは s/// を使って直接 的にでも split のような関数を使って間接的にでも呼び出さないで ください. Because perl's regex engine is not currently re-entrant, delayed code may not invoke the regex engine either directly with m// or s///), or indirectly with functions such as split.

入力を消費しない 50 回を超える深い再帰は致命的なエラーと なります. 最大深度は perl にコンパイルされているので, これを変更するには特別にビルドする必要があります. Recursing deeper than 50 times without consuming any input string will result in a fatal error. The maximum depth is compiled into perl, so changing it requires a custom build.

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

コードのコンパイルを伴わなず, その代わりにキャプチャバッファの 内容を現在の位置でマッチすべき独立したパターンとして 扱う, (??{ code }) と似た機能です. パターンに内包されている キャプチャバッファは一番外側の再帰として決定されるという 価値があります. Similar to (??{ code }) except it does not involve compiling any code, instead it treats the contents of a capture buffer as an independent pattern that must match at the current position. Capture buffers contained by the pattern will have the value as determined by the outermost recursion.

PARNO はその値が再帰させるキャプチャバッファの 括弧番号を反映する一連の数字からなります(そして0からは 始まりません). (?R) はパターン全体の最初から再帰します. (?0)(?R) の別の構文です. PARNO の前に正符号 若しくは負符号がついていた場合には相対的な位置として 使われます, 負数であれば前のキャプチャバッファを, 正数であれば続くキャプチャバッファを示します. 従って (-1) は一番最近宣言されたバッファを参照し, (?+1) は次に宣言されるバッファを参照します. 相対再帰の数え方は相対後方参照とは違って, バッファに閉じていない再帰は含まれることに 注意してください, PARNO is a sequence of digits (not starting with 0) whose value reflects the paren-number of the capture buffer to recurse to. (?R) recurses to the beginning of the whole pattern. (?0) is an alternate syntax for (?R). If PARNO is preceded by a plus or minus sign then it is assumed to be relative, with negative numbers indicating preceding capture buffers and positive ones following. Thus (?-1) refers to the most recently declared buffer, and (?+1) indicates the next buffer to be declared. Note that the counting for relative recursion differs from that of relative backreferences, in that with recursion unclosed buffers are included.

以下のパターンは引数にバランスのとれた括弧を 含んでいるかもしれない関数 foo() にマッチします. The following pattern matches a function foo() which may contain balanced parentheses as the argument.

  $re = qr{ (                    # paren group 1 (full function)
              foo
              (                  # paren group 2 (parens)
                \(
                  (              # paren group 3 (contents of parens)
                  (?:
                   (?> [^()]+ )  # Non-parens without backtracking
                  |
                   (?2)          # Recurse to start of paren group 2
                  )*
                  )
                \)
              )
            )
          }x;
  
  $re = qr{ (                    # 括弧グループ 1 (関数全体)
              foo
              (                  # 括弧グループ 2 (括弧)
                \(
                  (              # 括弧グループ 3 (括弧の内容)
                  (?:
                   (?> [^()]+ )  # 括弧以外, バックトラックなし
                  |
                   (?2)          # 括弧グループ2を再帰
                  )*
                  )
                \)
              )
            )
          }x;

このパターンを以下のように使うと, If the pattern was used as follows

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

次のように出力されます: the output produced should be the following:

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

もし対応するキャプチャバッファが定義されていなかったときには 致命的なエラーとなります. 入力を消費しない 50 回を超える深い再帰も致命的なエラーと なります. 最大深度は perl にコンパイルされているので, これを変更するには特別にビルドする必要があります. If there is no corresponding capture buffer defined, then it is a fatal error. Recursing deeper than 50 times without consuming any input string will also result in a fatal error. The maximum depth is compiled into perl, so changing it requires a custom build.

以下に後で使うパターンのために, qr// 構成子内で再帰を 埋め込むのに負数の参照を使うとどのように容易になるかを示します: The following shows how using negative indexing can make it easier to embed recursive patterns inside of a qr// construct for later use:

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

補足 このパターンは PCRE や Python での等価な形式の構成子と 同じように振る舞うわけではありません. Perl においては再帰グループの 中にバックトラックできますが, PCRE や Python ではグループへの 再帰はアトミックに扱われます. また, 修飾子はコンパイル時に解決 されるので, (?i:(?1)) や (?:(?i)(?1)) といった構成子は サブパターンがどのように処理されたかに影響されません. Note that this pattern does not behave the same way as the equivalent PCRE or Python construct of the same form. In Perl you can backtrack into a recursed group, in PCRE and Python the recursed into group is treated as atomic. Also, modifiers are resolved at compile time, so constructs like (?i:(?1)) or (?:(?i)(?1)) do not affect how the sub-pattern will be processed.

(?&NAME)

名前付きサブパターンへの再帰. 再帰する括弧が名前によって 決定される点以外は(?PARNO) と等価です. もし複数の括弧で 同じ名前を持っていた場合には一番左のものに再帰します. Recurse to a named subpattern. Identical to (?PARNO) except that the parenthesis to recurse to is determined by name. If multiple parentheses have the same name, then it recurses to the leftmost.

パターンのどこでも宣言されていない名前の参照はエラーになります. It is an error to refer to a name that is not declared somewhere in the pattern.

補足: Python 若しくは PCRE 正規表現エンジンに なれているプログラマが簡単になるように Perl 5.10 以降では (?&NAME) の代わりに (?P>NANE) を使うこともできるでしょう. NOTE: In order to make things easier for programmers with experience with the Python or PCRE regex engines the pattern (?P>NAME) may be used instead of (?&NAME) in Perl 5.10 or later.

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

条件付き式. (condition) は括弧でくるまれた数値(対応する 括弧対がマッチしたときに有効), 先読み/後読み/ゼロ幅で評価される 言明, 角括弧mしくはシングルクオートでくるまれた名前(その 名前のバッファがマッチしたときに有効), 若しくは特殊なシンボル (R) (再帰若しくは eval 内で評価されているときに真)の いずれかです. 加えて R には数字(対応するグループ内で 再帰しているときに真), もしくは &NAME, こちらの時は その名前のグループで再帰している時にのみ真, を続ける こともできます. Conditional expression. (condition) should be either an integer in parentheses (which is valid if the corresponding pair of parentheses matched), a look-ahead/look-behind/evaluate zero-width assertion, a name in angle brackets or single quotes (which is valid if a buffer with the given name matched), or the special symbol (R) (true when evaluated inside of recursion or eval). Additionally the R may be followed by a number, (which will be true when evaluated when recursing inside of the appropriate group), or by &NAME, in which case it will be true only when evaluated during recursion in the named group. >

可能な述語の要約を次に示します: Here's a summary of the possible predicates:

(1) (2) ...

その番号のキャプチャバッファが何かにマッチしたかどうかを 調べます. Checks if the numbered capturing buffer has matched something.

(<NAME>) ('NAME')

その名前のバッファが何かにマッチしたかどうかを 調べます. Checks if a buffer with the given name has matched something.

(?{ CODE })

コードブロックを条件として扱います. Treats the code block as the condition.

(R)

式が再帰の中で評価されているかどうかを調べます. Checks if the expression has been evaluated inside of recursion.

(R1) (R2) ...

式がそのn番目のキャプチャグループのすぐ内側で実行されて いるかどうかを調べます. これは次のものと等価な正規表現です, Checks if the expression has been evaluated while executing directly inside of the n-th capture group. This check is the regex equivalent of

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

言い換えると, これは完全な再帰スタックを調べるわけではありません. In other words, it does not check the full recursion stack.

(R&NAME)

(R1) と似ていて, この述語はその名前のつけられている 一番左のグループのすぐ内側で実行されているかどうかをしらべます( 一番左は (?NAME) と同じロジックです). これは完全なスタックを調べずに, 一番内部のアクティブな最近名前を 見ます. Similar to (R1), this predicate checks to see if we're executing directly inside of the leftmost group with a given name (this is the same logic used by (?&NAME) to disambiguate). It does not check the full stack, but only the name of the innermost active recursion.

(DEFINE)

この場合において, yes-pattern は直接は実行されず, no-pattern は 許可されていません. (?{0}) と似ていますがより効率的です. 詳細は次のようになります. In this case, the yes-pattern is never directly executed, and no no-pattern is allowed. Similar in spirit to (?{0}) but more efficient. See below for details.

例: For example:

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

これは括弧以外からなる固まりか括弧の中にあるそれらにマッチします. matches a chunk of non-parentheses, possibly included in parentheses themselves.

(DEFINE) は特殊な形式で, これはその yes-pattern を 直接は実行左図, no-pattern も許可していません. これは再帰メカニズムの中で利用することでのみ実行される サブパターンの定義を許可します. これによって, 選んだパターンと一緒に正規表現ルールを 定義することができます. A special form is the (DEFINE) predicate, which never executes directly its yes-pattern, and does not allow a no-pattern. This allows to define subpatterns which will be executed only by using the recursion mechanism. This way, you can define a set of regular expression rules that can be bundled into any pattern you choose.

この使い方において, DEFINE ブロックはパターンの最後におくこと, そしてそこで定義する全てのサブパターンに名前をつけることが 推奨されています. It is recommended that for this usage you put the DEFINE block at the end of the pattern, and that you name any subpatterns defined within it.

また, この方法によって定義されるパターンはその処理に関して そんなに賢い訳ではないので効率的でないことに 価値は何もないでしょう. Also, it's worth noting that patterns defined this way probably will not be as efficient, as the optimiser is not very clever about handling them.

これをどのように使うかの例を次に示します: An example of how this might be used is as follows:

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

再帰の内側でマッチしたキャプチャバッファは再帰から戻った後には アクセスできないため. キャプチャバッファのこの1段増えた レイヤは必要な点に注意してください. 従って $+{NAME} が定義されていても $+{NAME_PAT} は定義されません. Note that capture buffers matched inside of recursion are not accessible after the recursion returns, so the extra layer of capturing buffers is necessary. Thus $+{NAME_PAT} would not be defined even though $+{NAME} would be.

(?>pattern)

"独立した"部分式, スタンドアロンの pattern が その場所に固定されてマッチする部分文字列にマッチし, その文字列以外にはなにもマッチしません. この構成子は他の"外部"マッチになる最適化に便利です, なぜならこれはバックトラックしないためです("バックトラック"参照). これは "できる限りを取り込んで, 後は戻らない"セマンティクスが 必要な場所でも便利です. An "independent" subexpression, one which matches the substring that a standalone pattern would match if anchored at the given position, and it matches nothing other than this substring. This construct is useful for optimizations of what would otherwise be "eternal" matches, because it will not backtrack (see "Backtracking"). It may also be useful in places where the "grab all you can, and do not give anything back" semantic is desirable.

例: ^(?>a*)ab は何もマッチしません, なぜなら (?>a*) (前述のように, 文字列の開始で 固定されます)は文字列のはじめにある全ての文字 a にマッチし, ab のマッチのための a を残さないためです. 対照的に, a*aba+b と同じようにマッチします, これはサブグループ a* のマッチは次のグループ ab の 影響を受けるためです ("バックトラック"参照). 特に, a*ab の中の a* は単独の a* より短い文字にマッチ します, これによって最後のマッチが行えるようになります. For example: ^(?>a*)ab will never match, since (?>a*) (anchored at the beginning of string, as above) will match all characters a at the beginning of string, leaving no a for ab to match. In contrast, a*ab will match the same as a+b, since the match of the subgroup a* is influenced by the following group ab (see "Backtracking"). In particular, a* inside a*ab will match fewer characters than a standalone a*, since this makes the tail match.

(?>pattern) と似た効果は (?=(pattern))\1 でも達成できます. これは単独の a+ と同じ部分文字列にマッチし, それに続く \1 がマッチした文字列を消費します; これはゼロ幅の言明が (?>...) の類似を作るためです. (この2つの構成子は後者はグループをキャプチャするため, それに続く正規表現の残りで後方参照の順序をずらす点で 違いがあります). An effect similar to (?>pattern) may be achieved by writing (?=(pattern))\1. This matches the same substring as a standalone a+, and the following \1 eats the matched string; it therefore makes a zero-length assertion into an analogue of (?>...). (The difference between these two constructs is that the second one uses a capturing group, thus shifting ordinals of backreferences in the rest of a regular expression.)

次のパターンを考えてみてください: Consider this pattern: m{ \( ( [^()]+ # x+ | \( [^()]* \) )+ \) }x

これは2段階までの括弧でくるまれた空でないグループに 効率的にマッチします. しかしながら, これはマッチする グループがなかったときに長い文字列においてはほとんど 永遠に戻りません. これは長い文字列をいくつかの部分 文字列に分解する方法がいくつもあるためです. これは (.+)+ が行うことでもあり, (.+)+ は このパターンの部分パターンと似ています. このパターンが ((()aaaaaaaaaaaaaaaaaa にはマッチしないことを どうやって検出するかを少し考えてみましょう, しかしここでは余計な文字を2倍にしてみます. この指数的なパフォーマンスはプログラムの ハングアップとして表面化します. しかしながら, このパターンに小さな変更をいれてみます, That will efficiently match a nonempty group with matching parentheses two levels deep or less. However, if there is no such group, it will take virtually forever on a long string. That's because there are so many different ways to split a long string into several substrings. This is what (.+)+ is doing, and (.+)+ is similar to a subpattern of the above pattern. Consider how the pattern above detects no-match on ((()aaaaaaaaaaaaaaaaaa in several seconds, but that each extra letter doubles this time. This exponential performance will make it appear that your program has hung. However, a tiny change to this pattern

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

これは上で行っているように (?>...) マッチを 使っています(これは自身で確認してみるとよいでしょう), しかし 1000000 個の a からなる似た文字列を使ってみると, 4分の1の時間で完了します. しかしながら, このパターンは 現在のところ use warnings プラグマ若しくは -w スイッチ の影響下では "正規表現において空文字列に何回もマッチ しました (matches null string many times in regex)" という警告を発するでしょう. which uses (?>...) matches exactly when the one above does (verifying this yourself would be a productive exercise), but finishes in a fourth the time when used on a similar string with 1000000 as. Be aware, however, that this pattern currently triggers a warning message under the use warnings pragma or -w switch saying it "matches null string many times in regex".

パターン (?> [^()]+ ) のような簡単なグループでは, 比較できる影響は [^()]+ (?! [^()] ) のように負の先読みの 言明で達することができます. これは 1000000 個の a からなる 文字列において4倍だけ遅くなります. On simple groups, such as the pattern (?> [^()]+ ), a comparable effect may be achieved by negative look-ahead, as in [^()]+ (?! [^()] ). This was only 4 times slower on a string with 1000000 as.

最初の ()* のような正しい解法となる多くの状況において "できる限りを取り込んで, 後は戻らない"セマンティクスが 望まれるものです. 任意で(水平)白空白の続く # によって 区切られるコメントのついたテキストのパースを考えてみます. その出現と対比して, #[ \t]* はコメント区切りにマッチする 正しい部分式ではありません, なぜならパターンの残りがそれの マッチを作ることができるのならそれはいくつかの白空白を "あきらめてしまう"ためです. 正しい回答は以下のいずれかです: The "grab all you can, and do not give anything back" semantic is desirable in many situations where on the first sight a simple ()* looks like the correct solution. Suppose we parse text with comments being delimited by # followed by some optional (horizontal) whitespace. Contrary to its appearance, #[ \t]* is not the correct subexpression to match the comment delimiter, because it may "give up" some whitespace if the remainder of the pattern can be made to match that way. The correct answer is either one of these:

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

例えば空でないコメントを $1 に取り込むためには 次のいずれかを使います: For example, to grab non-empty comments into $1, one should use either one of these:

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

選んだ方はコメントの仕様をより適切に反映した式に 依存します. Which one you pick depends on which of these expressions better reflects the above specification of comments.

いくつかの書籍においてこの構成子は"アトミックなマッチ" 若しくは"強欲なマッチ(possessive matching)" と呼ばれます. In some literature this construct is called "atomic matching" or "possessive matching".

強欲な量指定しはそれが適用されている項目を これらの構成子の中に置くことと等価です. 以下の等式が適用されます: Possessive quantifiers are equivalent to putting the item they are applied to inside of one of these constructs. The following equivalences apply:

    Quantifier Form     Bracketing Form
    量指定子形式        バックトラック形式
    ---------------     ---------------
    PAT*+               (?>PAT*)
    PAT++               (?>PAT+)
    PAT?+               (?>PAT?)
    PAT{min,max}+       (?>PAT{min,max})

特殊なバックトラック制御記号 Special Backtracking Control Verbs

警告: これらのパターンは実験的なものであり, Perl の今後のバージョンで変更若しくは削除される可能性があります. 製品コードでこれらを使う際にはアップグレードによる問題を 避けるために明記するべきです. WARNING: These patterns are experimental and subject to change or removal in a future version of Perl. Their usage in production code should be noted to avoid problems during upgrades.

これらの特殊なパターンは (*VERB:ARG) という一般形式を 持っています. ARG が任意であると規定されていいないいくつかの ケース以外では, それは拒否されます. These special patterns are generally of the form (*VERB:ARG). Unless otherwise stated the ARG argument is optional; in some cases, it is forbidden.

引数を許可する特殊バックトラック制御記号を含んでいる 全てのパターンは, それが実行されると現在のパッケージの $REGERROR 及び $REGMARK 変数を設定する特殊な 振る舞いを持っています. これが行われる時 以下の手順が適用されます. Any pattern containing a special backtracking verb that allows an argument has the special behaviour that when executed it sets the current packages' $REGERROR and $REGMARK variables. When doing so the following rules apply:

失敗時には $REGERROR 変数には, 記号がマッチの失敗の中で 使われていたのならその記号パターンの ARG の値がセットされます. もしパターンの ARG 部分が省略されていたときには, $REGERROR には最後に実行された (*MARK:NAME) パターンの 名前, 若しくはそれもなければ真に設定されます. また, $REGMARK 変数は偽に設定されます. On failure, the $REGERROR variable will be set to the ARG value of the verb pattern, if the verb was involved in the failure of the match. If the ARG part of the pattern was omitted, then $REGERROR will be set to the name of the last (*MARK:NAME) pattern executed, or to TRUE if there was none. Also, the $REGMARK variable will be set to FALSE.

マッチの成功時には, $REGERROR 変数は偽に設定され, $REGMARK 変数には最後に実行された (*MARK:NAME) パターン の名前が設定されます. 詳細は (*MARK:NAME) 記号の説明を 参照してください. On a successful match, the $REGERROR variable will be set to FALSE, and the $REGMARK variable will be set to the name of the last (*MARK:NAME) pattern executed. See the explanation for the (*MARK:NAME) verb below for more details.

補足: $REGERROR 及び $REGMARK$1 や他の多くの 正規表現関連の変数のようにマジック変数ではありません. それらは スコープ内にローカルにならず, 読み込み専用でもありませんが, $AUTOLOAD と似た揮発するパッケージ変数です. 必要時に特定のスコープ内に変更を留めたいときには local を 使ってください. NOTE: $REGERROR and $REGMARK are not magic variables like $1 and most other regex related variables. They are not local to a scope, nor readonly, but instead are volatile package variables similar to $AUTOLOAD. Use local to localize changes to them to a specific scope if necessary.

もしパターンが引数を許可する特殊バックトラック記号を 含んでなかった場合には, $REGERROR 及び $REGMARK は全く 触られません. If a pattern does not contain a special backtracking verb that allows an argument, then $REGERROR and $REGMARK are not touched at all.

1つの引数を取る記号 Verbs that take an argument
(*PRUNE) (*PRUNE:NAME)

このゼロ幅のパターンは失敗でバックトラックしてきたときに 現在の位置でバックトラックツリーを刈り取ります. A (*PRUNE) B というパターンで A も B も複雑な パターンである時を考えてみます. (*PRUNE) に達するまでは, A はマッチに必要であればバックトラックしていきます. しかしいったんそこに達して B に続くと, そこでも 必要にお維持手バックトラックします; しかしながら, B がマッチしなかったときにはそれ以上のバックトラックは 行われず, 現在の開始位置でのマッチはすぐに失敗します. This zero-width pattern prunes the backtracking tree at the current point when backtracked into on failure. Consider the pattern A (*PRUNE) B, where A and B are complex patterns. Until the (*PRUNE) verb is reached, A may backtrack as necessary to match. Once it is reached, matching continues in B, which may also backtrack as necessary; however, should B not match, then no further backtracking will take place, and the pattern will fail outright at the current starting position.

次の例ではパターンに対してマッチできるすべての 文字列を(実際にはマッチさせずに)数えます. The following example counts all the possible matching strings in a pattern (without actually matching any of them).

    'aaab' =~ /a+b?(?{print "$&\n"; $count++})(*FAIL)/;
    print "Count=$count\n";

この出力: which produces:

    aaab
    aaa
    aa
    a
    aab
    aa
    a
    ab
    a
    Count=9

次のように数える前に (*PRUNE) を加えると If we add a (*PRUNE) before the count like the following

    'aaab' =~ /a+b?(*PRUNE)(?{print "$&\n"; $count++})(*FAIL)/;
    print "Count=$count\n";

バックトラックを妨げ次のように各開始位置での一番長いマッチを 数えるようになります: we prevent backtracking and find the count of the longest matching at each matching startpoint like so:

    aaab
    aab
    ab
    Count=3

1つのパターン内で (*PRUNE) 言明はいくつでも使えます. Any number of (*PRUNE) assertions may be used in a pattern.

バックトラックを制御する他の方法として (?>pattern) 及び強欲な量指定子も参照してください. 幾つかのケースにおいては (*PRUNE) の利用は機能的な違いなしに (?>pattern) で 置き換えることができます; しかしながら (*PRUNE)(?>pattern) 単独では表現できないケースを扱うために 使うことができます. See also (?>pattern) and possessive quantifiers for other ways to control backtracking. In some cases, the use of (*PRUNE) can be replaced with a (?>pattern) with no functional difference; however, (*PRUNE) can be used to handle cases that cannot be expressed using a (?>pattern) alone.

(*SKIP) (*SKIP:NAME)

このゼロ幅のパターンは *PRUNE と似ていますが, 実行されている (*SKIP) パターンまでにマッチした テキストはこのパターンのどのマッチの一部にもならないことを 示します. これは正規表現エンジンがこの位置まで失敗として "スキップ"して(マッチに十分な空間があれば)再びマッチを 試みることを効率的に意味します. This zero-width pattern is similar to (*PRUNE), except that on failure it also signifies that whatever text that was matched leading up to the (*SKIP) pattern being executed cannot be part of any match of this pattern. This effectively means that the regex engine "skips" forward to this position on failure and tries to match again, (assuming that there is sufficient room to match).

(*SKIP:NAME) パターンの名前部分には特別な意味があります. もしマッチにおいて (*MARK:NAME) に遭遇すると, それは"スキップ位置"として使われる位置になります. その名前の (*MARK) と東宮していなければ, (*SKIP) 操作は効果を持ちません. 名前がなければ"スキップ位置"は (*SKIP)パターンの実行されたときにマッチポイントが 使われます. The name of the (*SKIP:NAME) pattern has special significance. If a (*MARK:NAME) was encountered while matching, then it is that position which is used as the "skip point". If no (*MARK) of that name was encountered, then the (*SKIP) operator has no effect. When used without a name the "skip point" is where the match point was when executing the (*SKIP) pattern.

以下の例を (*PRUNE) と比べてみてください, 文字列が2倍になってることに注意してください: Compare the following to the examples in (*PRUNE), note the string is twice as long:

    'aaabaaab' =~ /a+b?(*SKIP)(?{print "$&\n"; $count++})(*FAIL)/;
    print "Count=$count\n";

出力 outputs

    aaab
    aaab
    Count=2

いったん文字列の最初の 'aaab' がマッチして, (*SKIP) が実行されると, 次の開始位置は (*SKIP) が 実行されたときのカーソルがいた位置になります. Once the 'aaab' at the start of the string has matched, and the (*SKIP) executed, the next startpoint will be where the cursor was when the (*SKIP) was executed.

(*MARK:NAME) (*:NAME)

このゼロ幅のマッチはパターン内の特定の箇所がマッチに成功 したときに, 文字列の中で達した位置を記録するために 使われます. このマークには名前をつけることもできます. 後者の (*SKIP) パターンは失敗時でバックトラックしたときに その箇所までスキップします. (*MARK) パターンはいくつでも 使うことができて, NAME 部分は省略可能であり重複することもあります. This zero-width pattern can be used to mark the point reached in a string when a certain part of the pattern has been successfully matched. This mark may be given a name. A later (*SKIP) pattern will then skip forward to that point if backtracked into on failure. Any number of (*MARK) patterns are allowed, and the NAME portion is optional and may be duplicated.

(*SKIP) パターンとの相互動作に加えて, (*MARK:NAME) はパターン分岐の"ラベル"としても 使うことができます, このためマッチの後で, プログラムは そのマッチにおいてパターンのどの分岐が使われたのかを 知ることができます. In addition to interacting with the (*SKIP) pattern, (*MARK:NAME) can be used to "label" a pattern branch, so that after matching, the program can determine which branches of the pattern were involved in the match.

マッチの成功時に, $REGMARK 変数はマッチの中で 一番最近に実行された (*MARK:NAME) の名前を設定します. When a match is successful, the $REGMARK variable will be set to the name of the most recently executed (*MARK:NAME) that was involved in the match.

これは書く分岐で別々のキャプチャバッファを使うことなしに パターンのどの分岐がマッチしたのかを知るために使うことが できます, これは perl は /(?:(x)|(y)|(z))//(?:x(*MARK:x)|y(*MARK:y)|z(*MARK:z))/ 程度に効率的には 最適化できないためパフォーマンスの向上をもたらします. This can be used to determine which branch of a pattern was matched without using a separate capture buffer for each branch, which in turn can result in a performance improvement, as perl cannot optimize /(?:(x)|(y)|(z))/ as efficiently as something like /(?:x(*MARK:x)|y(*MARK:y)|z(*MARK:z))/.

マッチが失敗して, そして他の記号がマッチの失敗で 行われずかつ名前を持っているというのでなければ, $REGERROR 変数には一番最近に実行された名前が設定されます. When a match has failed, and unless another verb has been involved in failing the match and has provided its own name to use, the $REGERROR variable will be set to the name of the most recently executed (*MARK:NAME).

詳細は (*SKIP) を参照してください. See (*SKIP) for more details.

(*MARK:NAME) の短縮形として (*:NAME) をも記述できます. As a shortcut (*MARK:NAME) can be written (*:NAME).

(*THEN) (*THEN:NAME)

これは Perl6 の "cut group" 演算子 :: と似ています. (*PRUNE) のように, この記号は常にマッチし, そして 失敗でバックトラックした時に正規表現エンジンに 一番内側で閉じているグループ(キャプチャでもそうでなくとも) で次の代替を試みるようにさせます. This is similar to the "cut group" operator :: from Perl6. Like (*PRUNE), this verb always matches, and when backtracked into on failure, it causes the regex engine to try the next alternation in the innermost enclosing group (capturing or otherwise).

この名前は代替演算子(|) と連結されたこの演算子で 本質的にパターンベースの if/then/else ブロックとなる ものを作るために使うことができることからきています: Its name comes from the observation that this operation combined with the alternation operator (|) can be used to create what is essentially a pattern-based if/then/else block:

  ( COND (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ )

この演算子が使われていてそしてそれが代替の内側ではなければ これはちょうど (*PRUNE) 演算子のように動作します. Note that if this operator is used and NOT inside of an alternation then it acts exactly like the (*PRUNE) operator.

  / A (*PRUNE) B /

は次と同じです is the same as

  / A (*THEN) B /

しかし but

  / ( A (*THEN) B | C (*THEN) D ) /

は次と同じではありません is not the same as

  / ( A (*PRUNE) B | C (*PRUNE) D ) /

A にマッチしたけれど B に失敗した後 (*THEN) 記号は バックトラックして C を試みます; しかし (*PRUNE) 記号であれば単純に失敗します. as after matching the A but failing on the B the (*THEN) verb will backtrack and try C; but the (*PRUNE) verb will simply fail.

(*COMMIT)

これは Perl6 の"コミットパターン" <commit> 若しくは ::: です. これは (*SKIP) と似たゼロ幅のパターンですが, 失敗でバックトラックした際にマッチがすぐに失敗する点で異なります. それ以降で開始位置を進めて有効なマッチを探す試行は行われません. 例えば, This is the Perl6 "commit pattern" <commit> or :::. It's a zero-width pattern similar to (*SKIP), except that when backtracked into on failure it causes the match to fail outright. No further attempts to find a valid match by advancing the start pointer will occur again. For example,

    'aaabaaab' =~ /a+b?(*COMMIT)(?{print "$&\n"; $count++})(*FAIL)/;
    print "Count=$count\n";

は次を出力します outputs

    aaab
    Count=1

言い換えると, いったん (*COMMIT) に入った後に, そのパターンがマッチしなかったのなら, 正規表現エンジンは 文字列の残りに対してそれ以上のマッチを試みません. In other words, once the (*COMMIT) has been entered, and if the pattern does not match, the regex engine will not try any further matching on the rest of the string.

引数をとらない記号 Verbs without an argument
(*FAIL) (*F)

このパターンは何にもマッチせず常に失敗します. これはエンジンを強制的にバックトラックさせるために 使うことができます. これは (?!) と等価ですが, より読みやすくなっています. 実際, (?!) は内部的には (*FAIL) に最適化されます. This pattern matches nothing and always fails. It can be used to force the engine to backtrack. It is equivalent to (?!), but easier to read. In fact, (?!) gets optimised into (*FAIL) internally.

これはおそらく (?{}) 若しくは (??{}) と組み合わせた 時にだけ役に立つでしょう. It is probably useful only when combined with (?{}) or (??{}).

(*ACCEPT)

警告: この機能は強く実験的です. 製品コードでは推奨されません. WARNING: This feature is highly experimental. It is not recommended for production code.

このパターンマッチは何もせず (*ACCEPT) パターンと遭遇した場所で 文字列の中で実際にもっとマッチするものがあるかどうかにかかわらず 成功のマッチを終了させます. 再帰, 若しくは (??{}) といった ネストしたパターンの内側では, 一番内側のパターンのみがすぐに終了します. This pattern matches nothing and causes the end of successful matching at the point at which the (*ACCEPT) pattern was encountered, regardless of whether there is actually more to match in the string. When inside of a nested pattern, such as recursion, or in a subpattern dynamically generated via (??{}), only the innermost pattern is ended immediately.

(*ACCEPT) がキャプチャバッファの内側で使われた場合 キャプチャバッファは (*ACCEPT) と遭遇した位置で 終了とマークされます. 例えば: If the (*ACCEPT) is inside of capturing buffers then the buffers are marked as ended at the point at which the (*ACCEPT) was encountered. For instance:

  'AB' =~ /(A (A|B(*ACCEPT)|C) D)(E)/x;

はマッチし, $1AB になり, $2B に, そして $3 は設定されません. 'ACDE' のように括弧の内側で他の分岐が マッチしたのなら, D 及び E もマッチします. will match, and $1 will be AB and $2 will be B, $3 will not be set. If another branch in the inner parentheses were matched, such as in the string 'ACDE', then the D and E would have to be matched as well.

バックトラック Backtracking

補足: このセクションでは正規表現の振る舞いに関する抽象的な概要を 説明します. 可能な代替におけるマッチの選択における ルールの厳密な(そして複雑な)説明は "Combining RE Pieces" を 参照してください. NOTE: This section presents an abstract approximation of regular expression behavior. For a more rigorous (and complicated) view of the rules involved in selecting a match among possible alternatives, see "Combining RE Pieces".

正規表現マッチの基本的な機能には 最近(必要であれば)すべての強欲でない正規表現量指定子, つまり, *, *?, +, +?, {n,m}, そして {n,m}? で 使われるバックトラッキングと呼ばれる概念が含まれています. A fundamental feature of regular expression matching involves the notion called backtracking, which is currently used (when needed) by all regular non-possessive expression quantifiers, namely *, *?, +, +?, {n,m}, and {n,m}?. Backtracking is often optimized internally, but the general principle outlined here is valid.

正規表現がマッチ知る時, その正規表現の一部ではなく, 全体がマッチしなければなりません.そのためもしパターンの 前半にパターンの後半部分を失敗させてしまう量指定子が含まれて いるのなら, マッチングエンジンはいったん戻って開始位置を再計算します -- これがバックトラッキングと呼ばれる所以です. For a regular expression to match, the entire regular expression must match, not just part of it. So if the beginning of a pattern containing a quantifier succeeds in a way that causes later parts in the pattern to fail, the matching engine backs up and recalculates the beginning part--that's why it's called backtracking.

バックトラッキングの例をあげてみます: "Foo is on the foo table." という文字列の中で "foo" に続く単語を取り出してください: Here is an example of backtracking: Let's say you want to find the word following "foo" in the string "Food is on the foo table.":

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

マッチが実行される時, 正規表現の最初の部分 (\b(foo)) は開始文字列の 右側で可能なマッチを探します, そして $1 に "Foo" をロードします. しかし, すぐにマッチエンジンは $1 に保存した "Foo" の後に白空白が 無いことを見つけ, それが失敗だったことを検出して仮にマッチさせた 場所の1文字後から開始します. この時次の "foo" の出現まで進みます. この時に正規表現は完全にマッチし, 予測した出力 "table follows foo." を 得ます. When the match runs, the first part of the regular expression (\b(foo)) finds a possible match right at the beginning of the string, and loads up $1 with "Foo". However, as soon as the matching engine sees that there's no whitespace following the "Foo" that it had saved in $1, it realizes its mistake and starts over again one character after where it had the tentative match. This time it goes all the way until the next occurrence of "foo". The complete regular expression matches this time, and you get the expected output of "table follows foo."

最小マッチが役立つこともあります. "foo" と "bar" の間の全てにマッチしたいと考えてください. 最初に, 次のように書くかもしれません: Sometimes minimal matching can help a lot. Imagine you'd like to match everything between "foo" and "bar". Initially, you write something like this:

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

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

  got <d is under the bar in the >

これは .* が貪欲であり, そのために最初の "foo" と 最後の "bar" の間にある全てを取り出してしまいます. 次に "foo" とその後の最初の "bar" の間にあるテキストを 取り出す最小マッチを使ったもっと効率的な方法を示します: That's because .* was greedy, so you get everything between the first "foo" and the last "bar". Here it's more effective to use minimal matching to make sure you get the text between a "foo" and the first "bar" thereafter.

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

別の例も出してみます. 文字列の最後にある数字にマッチさせて, そのマッチの前の部分も保持させてみましょう. そしてあなたは次のように書くかもしれません. Here's another example. Let's say you'd like to match a number at the end of a string, and you also want to keep the preceding part of the match. So you write this:

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

これは全く動作しません, なぜなら .* は貪欲であり 文字列全体を飲み込んでしまいます. \d* は空の文字列に マッチできるので正規表現は完全に正常にでマッチします. That won't work at all, because .* was greedy and gobbled up the whole string. As \d* can match on an empty string the complete regular expression matched successfully.

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

動作しない主なバリエーションをあげておきます: Here are some variants, most of which don't work:

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

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

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

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

このように, これは幾分トリッキーです. 重要なのは正規表現は成功の定義を定める主張の集合にすぎない ことを認識することです. 特定の文字列で成功となる定義には 0, 1, 若しくは複数の違ったやり方が存在します. そしてもし成功する複数の方法が存在するのなら 成功したうちのどれが目的とするものなのかを 知るためにバックトラッキングを理解しておく必要があります. As you see, this can be a bit tricky. It's important to realize that a regular expression is merely a set of assertions that gives a definition of success. There may be 0, 1, or several different ways that the definition might succeed against a particular string. And if there are multiple ways it might succeed, you need to understand backtracking to know which variety of success you will achieve.

前読みの言明及び否定を使っている時には これはますますトリッキーになります. "123" が後ろに続かない数字以外の列を探したいと考えてみてください. あなたは次のように書くかもしれません. When using look-ahead assertions and negations, this can all get even trickier. Imagine you'd like to find a sequence of non-digits not followed by "123". You might try to write that as

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

ですがこれはマッチしません; 少なくともなってほしかったようには. これは文字列の中に 123 がないことを要求します. よくある予想と比較してなぜパターンがマッチするのかの わかりやすい説明を次にしめします: But that isn't going to match; at least, not the way you're hoping. It claims that there is no 123 in the string. Here's a clearer picture of why that pattern matches, contrary to popular expectations:

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

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

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

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

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

テスト3はテスト1のより一般的なバージョンなので それが失敗すると考えたかもしれません. この2つの 重要な違いは, テスト3には量指定子(\D*)が含まれているので テスト1ではできなかったバックトラッキングを行うことが できるところにあります. ここであなたは "$x のはじめで 0個以上の非数字があるから 123 じゃない何かを得られるんじゃないの?" と聞くでしょう. このパターンマッチが \D* を "ABC" に展開させると これはパターン全体を失敗させることになります. You might have expected test 3 to fail because it seems to a more general purpose version of test 1. The important difference between them is that test 3 contains a quantifier (\D*) and so can use backtracking, whereas test 1 will not. What's happening is that you've asked "Is it true that at the start of $x, following 0 or more non-digits, you have something that's not 123?" If the pattern matcher had let \D* expand to "ABC", this would have caused the whole pattern to fail.

探索エンジンは最初に \D* を "ABC" にマッチさせます. そして (?!123) を "123" にマッチさせ, これは失敗します. けれども量指定子 (\D*) が 正規表現の中で使われているので, 探索エンジンはバックトラックして この正規表現全体をマッチさせるように異なるマッチを 行うことができます. The search engine will initially match \D* with "ABC". Then it will try to match (?!123) with "123", which fails. But because a quantifier (\D*) has been used in the regular expression, the search engine can backtrack and retry the match differently in the hope of matching the complete regular expression.

このパターンは本当に, 本当に成功したいので, これは標準的なパターンの後退再試行を行い, この時に \D* を "AB" のみに展開させます. そして確かに "AB" の後ろは "123" ではありません. "C123" は十分満たしています. The pattern really, really wants to succeed, so it uses the standard pattern back-off-and-retry and lets \D* expand to just "AB" this time. Now there's indeed something following "AB" that is not "123". It's "C123", which suffices.

これは言明と否定の両方を使うことで処理することができます. $1 の最初の部分は数字が続きかつそれは "123" ではないことを 宣言します. 先読みはゼロ幅の式なのでそれが マッチした文字列を全く消費しないことを思い出してください. そしてこれを必要なものを生成するように書き換えます; つまり, 5 のケースでは失敗し, 6 のケースは成功します: We can deal with this by using both an assertion and a negation. We'll say that the first part in $1 must be followed both by a digit and by something that's not "123". Remember that the look-aheads are zero-width expressions--they only look, but don't consume any of the string in their match. So rewriting this way produces what you'd expect; that is, case 5 will fail, but case 6 succeeds:

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

    6: got ABC

言い換えると, このそれぞれの次にある2つのゼロ幅の言明は ちょうど何か組み込みの言明を使ったかのように それらがともに AND されているかのように動作します: /^$/ は行の始まりで且つ同時に行の終了でる時にのみ マッチします. もっと深部での真実は, 併記された正規表現は 垂直線を使って明示的に OR を書いたとき以外は常に AND を意味します. /ab/ は, "a" がゼロ幅の言明ではなく 1文字幅の言明なので異なる場所でマッチが行われはしますが, "a" にマッチ且つ(そして) "b" にマッチということを意味します. In other words, the two zero-width assertions next to each other work as though they're ANDed together, just as you'd use any built-in assertions: /^$/ matches only if you're at the beginning of the line AND the end of the line simultaneously. The deeper underlying truth is that juxtaposition in regular expressions always means AND, except when you write an explicit OR using the vertical bar. /ab/ means match "a" AND (then) match "b", although the attempted matches are made at different positions because "a" is not a zero-width assertion, but a one-width assertion.

警告: 特にコンパイルされた正規表現はマッチのために できる限りのバックトラックを非常に多くの回数行うので 解くために指数的な時間を必要とすることがあります. 例えば, 正規表現エンジンの内部で行われる 最適化がなかったときには, 次の評価は尋常じゃないくらい 長時間かかります: WARNING: Particularly complicated regular expressions can take exponential time to solve because of the immense number of possible ways they can use backtracking to try for a match. For example, without internal optimizations done by the regular expression engine, this will take a painfully long time to run:

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

そしてもし内側のグループで 0 から 5 回にマッチを制限する代わりに * を使うと, 永久に, 若しくはスタックを使い果たすまで 実行し続けることになります. その上, これらの最適化は 常にできるわけではありません. 例えば, 外側のグループで * の代わりに {0,5} を使ったときに, 現在の 最適化は適用されません, そしてマッチが終わるまでの 長い時間が必要になります. And if you used *'s in the internal groups instead of limiting them to 0 through 5 matches, then it would take forever--or until you ran out of stack space. Moreover, these internal optimizations are not always applicable. For example, if you put {0,5} instead of * on the external group, no current optimization is applicable, and the match takes a long time to finish.

そのような野獣のような最適化のための パワフルなツールとして知られているものに, "独立グループ" があります, これはバックトラックを行いません ("C<< (?>pattern) >>" を参照). ゼロ幅の先読み/後読みの言明も"論理的な"文脈なので 末尾のマッチをバックトラックしません: マッチが関連して 考慮されるかどうかだけです. 先読みの言明の副作用が それに続くマッチに影響するかもしれない例は, "C<< (?>pattern) >>" を参照してください. A powerful tool for optimizing such beasts is what is known as an "independent group", which does not backtrack (see "C<< (?>pattern) >>"). Note also that zero-length look-ahead/look-behind assertions will not backtrack to make the tail match, since they are in "logical" context: only whether they match is considered relevant. For an example where side-effects of look-ahead might have influenced the following match, see "C<< (?>pattern) >>".

バージョン 8 正規表現 Version 8 Regular Expressions

"通常の"バージョン 8 正規表現ルーチンに詳しくないので あれば, ここにはこれまでに説明されていないパターンマッチ ルールがあります. In case you're not familiar with the "regular" Version 8 regex routines, here are the pattern-matching rules not described above.

すべての単一の文字は, それが個々で若しくはこれまでに 説明した特別な意味を持っているメタ文字である場合 意外は, 文字それ自身にマッチします. 文字は "\" で前置されることで通常はメタ文字としての 機能を持っている文字をリテラルとして処理させれるように なります(つまり, "\." は任意の1文字ではなく "." にマッチするようになり. "\\" は "\" に マッチするようになります. このエスケープ機構は パターン区切りとして使われている文字でも必要です. Any single character matches itself, unless it is a metacharacter with a special meaning described here or above. You can cause characters that normally function as metacharacters to be interpreted literally by prefixing them with a "\" (e.g., "\." matches a ".", not any character; "\\" matches a "\"). This escape mechanism is also required for the character used as the pattern delimiter.

一連の文字は対象とする文字列の中で同じ一連の文字列に マッチします, なので blurfl というパターンは 対象とする文字列の中の "blurfl" にマッチします. A series of characters matches that series of characters in the target string, so the pattern blurfl would match "blurfl" in the target string.

[] で文字のリストを囲むことで文字クラスを 指定することができます, これはリストの中の 任意の文字にマッチします. もし "[" の後の 最初の文字が "^" だったときには, その文字クラスは リストの中にない任意の文字にマッチします. リストの中では, 文字 "-" は範囲を意味します, なので a-z は "a" と "z" を含めてそれらの間にある すべての文字を表現します, 文字クラスの要素として "-" 若しくは "]" を使いたい時には, リストの先頭に(あるいは"^"の後に)置くか, バックスラッシュを使ってエスケープします. "-" はリストの終端, リストを閉じる "]" の直前にあったときも リテラルとして扱われます. (次の例はすべて同じ3文字からなる文字クラスです: [-az], [az-], そして [a\-z]. これらはすべて EBCDICベースの文字集合であっても26文字からなる文字集合 [a-z] とは異なります.) また, 範囲の端点として 文字クラス \w, \W, \s, \S, \d, 若しくは \D を使ったときも "-" はリテラルとして 処理されます. You can specify a character class, by enclosing a list of characters in [], which will match any character from the list. If the first character after the "[" is "^", the class matches any character not in the list. Within a list, the "-" character specifies a range, so that a-z represents all characters between "a" and "z", inclusive. If you want either "-" or "]" itself to be a member of a class, put it at the start of the list (possibly after a "^"), or escape it with a backslash. "-" is also taken literally when it is at the end of the list, just before the closing "]". (The following all specify the same class of three characters: [-az], [az-], and [a\-z]. All are different from [a-z], which specifies a class containing twenty-six characters, even on EBCDIC-based character sets.) Also, if you try to use the character classes \w, \W, \s, \S, \d, or \D as endpoints of a range, the "-" is understood literally.

範囲全体というアイデアは文字集合間で ポータブルではありません -- そして 結果となる文字集合では予期したものではないでしょう. 音の原則では同じケースの英字の([a-e], [A-E]), 若しくは数字([0-9])という範囲でのみ使われています. これ以外は安全ではありません. もし信じられないのであれば 文字集合を完全につづってみてください. Note also that the whole range idea is rather unportable between character sets--and even within character sets they may cause results you probably didn't expect. A sound principle is to use only ranges that begin from and end at either alphabetics of equal case ([a-e], [A-E]), or digits ([0-9]). Anything else is unsafe. If in doubt, spell out the character sets in full.

文字は C でよく使われているようなメタ文字の構文を 使ってしているすることもできます: "\n" は改行に マッチし, "\t" はタブに, "\r" は復帰に, "\f" はフォームフィードにといった具合にマッチします. より一般的に, \nnn (nnn は8進数字) は その文字集合でコード値 nnn の文字にマッチします. 同じように, , \xnn (nn は16進数字) は 数値で nnn になる文字にマッチします. 式 \cx は制御文字 x にマッチします. そして最後に, "." メタ文字は "\n" 以外の任意の文字に マッチします(/sを使っているとき以外). Characters may be specified using a metacharacter syntax much like that used in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return, "\f" a form feed, etc. More generally, \nnn, where nnn is a string of octal digits, matches the character whose coded character set value is nnn. Similarly, \xnn, where nn are hexadecimal digits, matches the character whose numeric value is nn. The expression \cx matches the character control-x. Finally, the "." metacharacter matches any character except "\n" (unless you use /s).

"|" を使ってパターンを区切って一連の代替を指定する こともできます, なので fee|fie|foe は対象の文字列の "fee", "fie", 若しくは "foe" のいずれかに (f(e|i|o)e のように)マッチします. 最初の代替には最後のパターン区切り ("(", "[", 若しくはパターンの始まり)から最初の "|" までのすべてが含まれ, 最後の代替には最後の "|" から 次のパターン区切りまでが含まれます. 通常代替を括弧の中に 入れるのは, その開始位置と終了位置が少しはわかりやすく なるようにです. You can specify a series of alternatives for a pattern using "|" to separate them, so that fee|fie|foe will match any of "fee", "fie", or "foe" in the target string (as would f(e|i|o)e). The first alternative includes everything from the last pattern delimiter ("(", "[", or the beginning of the pattern) up to the first "|", and the last alternative contains everything from the last "|" to the next pattern delimiter. That's why it's common practice to include alternatives in parentheses: to minimize confusion about where they start and end.

代替は左から右へと試されます, なので最初の代替が その完全な式でマッチしたのならそれが選択されます. これは代替は貪欲である必要はないということを意味します. 例えば: "barefoot" に対して foo|foot をマッチさせると, 最初の代替から試されるので, "foo" の部分がマッチし, これは対象の文字列に対して成功でマッチします. (これは重要ではないでしょうが, 括弧を使ってマッチした テキストをキャプチャしているときには重要でしょう). Alternatives are tried from left to right, so the first alternative found for which the entire expression matches, is the one that is chosen. This means that alternatives are not necessarily greedy. For example: when matching foo|foot against "barefoot", only the "foo" part will match, as that is the first alternative tried, and it successfully matches the target string. (This might not seem important, but it is important when you are capturing matched text using parentheses.)

また "|" は角括弧の中ではリテラルとして処理されるので, [fee|fie|foe] と書くとこれは実際には [feio|] にのみ マッチします. Also remember that "|" is interpreted as a literal within square brackets, so if you write [fee|fie|foe] you're really only matching [feio|].

パターンにおいて, 後で参照するために括弧で括って 部分パターンを指定することができます, そしてメタ文字 \n を使ってパターンの後の方で n 番目の部分パターンを 参照することができます. 部分パターンは その開き括弧の左から右への順に番号づけられます. 後方参照は評価された文字列の中でその部分パターンに 実際にマッチしたものにマッチします. 従って, (0|0x)\d*\s\1\d* は "0x1234 0x4321" には マッチしますが, "0x1234 01234" にはマッチしません, なぜなら, 0|0x は2つめ数字の の先頭にある 0 にマッチすることができるのですが, 部分パターン 1 は "0x" にマッチするためです. Within a pattern, you may designate subpatterns for later reference by enclosing them in parentheses, and you may refer back to the nth subpattern later in the pattern using the metacharacter \n. Subpatterns are numbered based on the left to right order of their opening parenthesis. A backreference matches whatever actually matched the subpattern in the string being examined, not the rules for that subpattern. Therefore, (0|0x)\d*\s\1\d* will match "0x1234 0x4321", but not "0x1234 01234", because subpattern 1 matched "0x", even though the rule 0|0x could potentially match the leading 0 in the second number.

$1 ではなく \1 だったときの警告 Warning on \1 Instead of $1

次のように書くことになれている人も中にはいるでしょう: Some people get too used to writing things like:

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

sed 中毒な人をびっくりさせないための RHS 置換の祖先ですが, しかしこれは汚らしい癖です. Perl においては, s/// の右側はダブルクオートされた 文字列と考えられるためです. 通常のダブルクオートされた文字列の中では \1 は control-A を意味します. \1 の Unix での 習慣的な意味は s/// だけのその場しのぎです. しかしながら, この癖に漬かっていると /e 修飾子を 使ったときにトラブルとなるでしょう. This is grandfathered for the RHS of a substitute to avoid shocking the sed addicts, but it's a dirty habit to get into. That's because in PerlThink, the righthand side of an s/// is a double-quoted string. \1 in the usual double-quoted string means a control-A. The customary Unix meaning of \1 is kludged in for s///. However, if you get into the habit of doing that, you get yourself into trouble if you then add an /e modifier.

    s/(\d+)/ \1 + 1 /eg;    	# causes warning under -w

若しくは次のようにするかもしれません Or if you try to do

    s/(\d+)/\1000/;

これを解消するために \{1}000 としないでください, ここでは ${1}000 とするべきです. 埋め込みの処理は 後方参照にマッチさせる操作より混乱は少ないでしょう. 特に s///側では2つの異なった意味になります. You can't disambiguate that by saying \{1}000, whereas you can fix it with ${1}000. The operation of interpolation should not be confused with the operation of matching a backreference. Certainly they mean two different things on the left side of the s///.

ゼロ幅の部分文字列にマッチするパターンの繰り返し Repeated Patterns Matching a Zero-length Substring

警告: この先には難しい(そして無味乾燥な)物体が あります. このセクションは書き直す必要があるでしょう. WARNING: Difficult material (and prose) ahead. This section needs a rewrite.

正規表現は簡潔でパワフルなプログラミング言語を 提供します. 他の多くの強力なツールとともに, 力は破壊の源にもなります. Regular expressions provide a terse and powerful programming language. As with most other power tools, power comes together with the ability to wreak havoc.

この力のよくある乱用は無害な何かとともに, 正規表現使った無限ループとなります. A common abuse of this power stems from the ability to make infinite loops using regular expressions, with something as innocuous as:

    'foo' =~ m{ ( o? )* }x;

o?'foo' の始まりにマッチし, 文字列中での位置はこのマッチでは動かないので, o?* 量指定子によって何回もマッチします. 同じような繰り返しを作るもう一つのよくある形として //g 修飾子を使ったループがあります: The o? matches at the beginning of 'foo', and since the position in the string is not moved by the match, o? would match again and again because of the * quantifier. Another common way to create a similar cycle is with the looping modifier //g:

    @matches = ( 'foo' =~ m{ o? }xg );

若しくは or

    print "match: <$&>\n" while 'foo' =~ m{ o? }xg;

若しくは split() による暗黙のループ. or the loop implied by split().

しかしながら, 長きにわたる経験から いくつかのプログラミングタスクはゼロ幅の部分文字列 に対するマッチを行う部分式の繰り返しで 大幅に単純にできることがわかりました. 簡単な例を挙げてみます: However, long experience has shown that many programming tasks may be significantly simplified by using repeated subexpressions that may match zero-length substrings. Here's a simple example being:

    @chars = split //, $string;		  # // is not magic in split
    ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /

このように Perl は強制的に無限ループを砕くことによって こういった構築を可能にしています. このためのルールは 貪欲な量指定子 *+{} によって与えられる 低レベルなループとも, /g 修飾子や split() 演算子による 高レベルなループとも異なります. Thus Perl allows such constructs, by forcefully breaking the infinite loop. The rules for this are different for lower-level loops given by the greedy quantifiers *+{}, and for higher-level ones like the /g modifier or split() operator.

低レベルなループは Perl がゼロ幅の部分文字列に 対してマッチする式が繰り返されたことを検出すると 中断されます (つまり, ループは壊されます)> The lower-level loops are interrupted (that is, the loop is broken) when Perl detects that a repeated expression matched a zero-length substring. Thus

   m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;

は次と等価にされます is made equivalent to

   m{   (?: NON_ZERO_LENGTH )*
      |
        (?: ZERO_LENGTH )?
    }x;

高レベルのループは各繰り返しの間に最後のマッチが ゼロ幅だったかどうかを追加で保持しています. ループを終えるために, ゼロ幅のマッチの後のマッチは ゼロ幅となることを拒否します. この禁則処理は バックトラックと相互に動作し("バックトラッキング"参照), そして ベストなマッチがゼロ幅だったのなら 2番目にベストな マッチが選択されます. The higher level-loops preserve an additional state between iterations: whether the last match was zero-length. To break the loop, the following match after a zero-length match is prohibited to have a length of zero. This prohibition interacts with backtracking (see "Backtracking"), and so the second best match is chosen if the best match is of zero length.

例: For example:

    $_ = 'bar';
    s/\w??/<$&>/g;

これは <><b><><a><><r><> となります. 文字列の各位置に於いて, 貪欲でない ?? によって 得られるベストなマッチは ゼロ幅のマッチです, そして 2番目にベストなマッチは \w によって マッチするものです. 従ってゼロ幅のマッチは 1文字幅のマッチの代替となります. results in <><b><><a><><r><>. At each position of the string the best match given by non-greedy ?? is the zero-length match, and the second best match is what is matched by \w. Thus zero-length matches alternate with one-character-long matches.

同じように, m/()/g の繰り返しでは 文字列中の境界1つ遠い位置に2番目にベストな マッチがマッチします. Similarly, for repeated m/()/g the second-best match is the match at the position one notch further in the string.

ゼロ幅にマッチしているという追加の状態は マッチした文字列に関連づけられていて, pos() に対する 割り当てによってリセットされます. 前のマッチの終端でのゼロ幅のマッチは split の 間は無視されます. The additional state of being matched with zero-length is associated with the matched string, and is reset by each assignment to pos(). Zero-length matches at the end of the previous match are ignored during split.

RE の欠片の結合 Combining RE Pieces

これまでに説明された (ab\Z といった) 正規表現の基本的な欠片それぞれは, 入力文字列上の 与えられた位置で多くとも1つの部分文字列にマッチします. しかしながら, 典型的な正規表現ではこれらの基本的な 欠片は結合演算 ST, S|T, S* 等(ここで ST は正規表現の部分式)を使ってより複雑な パターンへと合成することができます. Each of the elementary pieces of regular expressions which were described before (such as ab or \Z) could match at most one substring at the given position of the input string. However, in a typical regular expression these elementary pieces are combined into more complicated patterns using combining operators ST, S|T, S* etc (in these examples S and T are regular subexpressions).

このような合成には選択の問題を導くために代替を 含めることができます: 正規表現 a|ab"abc" に対してマッチさせようとしたとき, これは "a""ab" のどちらにマッチするのか? 実際にどちらがマッチするのかを説明する1つの方法として, バックトラッキングのコンセプトがあります("Backtracking" 参照). しかしながら, この説明は低レベルすぎて 特定の実装を考えなければなりません. Such combinations can include alternatives, leading to a problem of choice: if we match a regular expression a|ab against "abc", will it match substring "a" or "ab"? One way to describe which substring is actually matched is the concept of backtracking (see "Backtracking"). However, this description is too low-level and makes you think in terms of a particular implementation.

もう一つの説明は"より良い"/"より悪い"の考え方で 始めます. 与えられた正規表現にマッチするすべての 部分文字列は"最良の"マッチから"最悪の"マッチへと ソートすることができます, そして "最良の"マッチが 選択されます. これは"どれが選ばれるのか?"という問いかけを "どのマッチがより良くて, それがより悪いのか?"という 問いかけに置き換えることができます. Another description starts with notions of "better"/"worse". All the substrings which may be matched by the given regular expression can be sorted from the "best" match to the "worst" match, and it is the "best" match which is chosen. This substitutes the question of "what is chosen?" by the question of "which matches are better, and which are worse?".

そして, 基本的な要素ではそういった問いかけはありません, なぜならこれらは与えられた位置で可能なマッチは 多くとも1つだからです. このセクションでは 結合演算のより良い/より悪いの考え方で説明していきます. 以下の説明では S 及び T は正規表現の部分式です. Again, for elementary pieces there is no such question, since at most one match at a given position is possible. This section describes the notion of better/worse for combining operators. In the description below S and T are regular subexpressions.

ST

2つの可能なマッチ, AB 及び A'B' を考えます, ここで A 及び A'S にマッチする部分文字列, そして B 及び B'T にマッチする部分文字列とします. Consider two possible matches, AB and A'B', A and A' are substrings which can be matched by S, B and B' are substrings which can be matched by T.

もし AS に対して A' よりも良いマッチであれば, ABA'B' よりも良いマッチです. If A is better match for S than A', AB is a better match than A'B'.

もし AA' が同じであれば: BT に対して B' よりも良いマッチであれば ABAB' よりも良いマッチです. If A and A' coincide: AB is a better match than AB' if B is better match for T than B'.

S|T

S がマッチできる時は T のみがマッチするよりも良いマッチです. When S can match, it is a better match than when only T can match.

S に対する2つのマッチの順序は S と同じです. T に対する2つのマッチも同様です. Ordering of two matches for S is the same as for S. Similar for two matches for T.

S{REPEAT_COUNT}

SSS...S (必要なだけ繰り返し)としてマッチします. Matches as SSS...S (repeated as many times as necessary).

S{min,max}

S{max}|S{max-1}|...|S{min+1}|S{min} としてマッチします. Matches as S{max}|S{max-1}|...|S{min+1}|S{min}.

S{min,max}?

S{min}|S{min+1}|...|S{max-1}|S{max} としてマッチします. Matches as S{min}|S{min+1}|...|S{max-1}|S{max}.

S?, S*, S+

それぞれ S{0,1}, S{0,BIG_NUMBER}, S{1,BIG_NUMBER} と同じです. Same as S{0,1}, S{0,BIG_NUMBER}, S{1,BIG_NUMBER} respectively.

S??, S*?, S+?

それぞれ S{0,1}?, S{0,BIG_NUMBER}?, S{1,BIG_NUMBER}? と同じです. Same as S{0,1}?, S{0,BIG_NUMBER}?, S{1,BIG_NUMBER}? respectively.

(?>S)

S の最良のみマッチします. Matches the best match for S and only that.

(?=S), (?<=S)

S の最良のマッチのみが考慮されます. (これは S がキャプチャ括弧を持っていて, そして正規表現全体の どこかで後方参照が使われている時のみ重要です.) Only the best match for S is considered. (This is important only if S has capturing parentheses, and backreferences are used somewhere else in the whole regular expression.)

(?!S), (?<!S)

このグループ演算子では, S がマッチできるかどうかのみが重要なので, 順序についての説明は必要ありません. For this grouping operator there is no need to describe the ordering, since only whether or not S can match is important.

(??{ EXPR }), (?PARNO)

順序は EXPR の結果の正規表現, 若しくはキャプチャバッファ PARNO に含まれているパターンと同じです. The ordering is the same as for the regular expression which is the result of EXPR, or the pattern contained by capture buffer PARNO.

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

既に決定している yes-pattern 若しくは no-pattern を 実際にマッチさせます. マッチの順序は選択された 部分式と同じです. Recall that which of yes-pattern or no-pattern actually matches is already determined. The ordering of the matches is the same as for the chosen subexpression.

ここにあげたレシピは与えられた位置でのマッチの順序について 説明しています. 正規表現全体でマッチがどのように決定されるかを 理解するためにはもう少しルールが必要です: より若い位置でのマッチは後ろの方でのマッチよりもより良いです. The above recipes describe the ordering of matches at a given position. One more rule is needed to understand how a match is determined for the whole regular expression: a match at an earlier position is always better than a match at a later position.

カスタム RE エンジンの作成 Creating Custom RE Engines

オーバーロードされた定数(overload 参照)を使って RE エンジンの機能を拡張する簡単な方法を提供することができます. Overloaded constants (see overload) provide a simple way to extend the functionality of the RE engine.

新しい正規表現エスケープシーケンス, 白空白文字と非白空白文字との 境界にマッチする \Y| を作ってみることにします. この位置には実際には (?=\S)(?<!\S)|(?!\S)(?<=\S) がマッチするので, この複雑なバージョンを \Y| で置き換えたいとします. このために customre モジュールを作ります: Suppose that we want to enable a new RE escape-sequence \Y| which matches at a boundary between whitespace characters and non-whitespace characters. Note that (?=\S)(?<!\S)|(?!\S)(?<=\S) matches exactly at these positions, so we want to have each \Y| in the place of the more complicated version. We can create a module customre to do this:

    package customre;
    use overload;

    sub import {
      shift;
      die "No argument to customre::import allowed" if @_;
      overload::constant 'qr' => \&convert;
    }

    sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}

    # We must also take care of not escaping the legitimate \\Y|
    # sequence, hence the presence of '\\' in the conversion rules.
    my %rules = ( '\\' => '\\\\',
		  'Y|' => qr/(?=\S)(?<!\S)|(?!\S)(?<=\S)/ );
    sub convert {
      my $re = shift;
      $re =~ s{
                \\ ( \\ | Y . )
              }
              { $rules{$1} or invalid($re,$1) }sgex;
      return $re;
    }

これで use customre することで正規表現定数の中で 新しいエスケープを使うことが出来ます, すなわち, これには何の実行時変数の埋め込みもいりません. overload に書かれているように, この変換は 正規表現のリテラル部分にのみ動作します. \Y|$re\Y| であれば この正規表現の変数部分は明示的に変換する必要があります (とはいえ $re の中でも \Y| を有効にしたい時のみ). Now use customre enables the new escape in constant regular expressions, i.e., those without any runtime variable interpolations. As documented in overload, this conversion will work only over literal parts of regular expressions. For \Y|$re\Y| the variable part of this regular expression needs to be converted explicitly (but only if the special meaning of \Y| should be enabled inside $re):

    use customre;
    $re = <>;
    chomp $re;
    $re = customre::convert $re;
    /\Y|$re\Y|/;

PCRE/Python サポート PCRE/Python Support

Perl 5.10 では Perl は幾つかの Python/PCRE 的な 正規表現構文拡張をサポートします. Perl プログラマはこれらの Perl としての構文を推奨しますが, 以下の物も Perl 5.10 では有効です: As of Perl 5.10 Perl supports several Python/PCRE specific extensions to the regex syntax. While Perl programmers are encouraged to use the Perl specific syntax, the following are legal in Perl 5.10:

(?P<NAME>pattern)

名前付のキャプチャバッファの定義. (?<NAME>pattern) と等価. Define a named capture buffer. Equivalent to (?<NAME>pattern).

(?P=NAME)

名前付キャプチャバッファへの後方参照. \g{NAME} と等価. Backreference to a named capture buffer. Equivalent to \g{NAME}.

(?P>NAME)

名前付きキャプチャバッファへの関数呼び出し. (?&NAME) と等価. Subroutine call to a named capture buffer. Equivalent to (?&NAME).


バグ BUGS

このドキュメントは完全にそして徹底的に不明瞭に理解するには 難しくありません. jargon に満ちたとりとめのない散文は 幾つかの箇所で理解するのに難儀ではあるでしょう. This document varies from difficult to understand to completely and utterly opaque. The wandering prose riddled with jargon is hard to fathom in several places.

このドキュメントはリファレンスの内容からチュートリアルを分離して 書き直す必要があるでしょう. This document needs a rewrite that separates the tutorial content from the reference content.


関連項目 SEE ALSO

perlrequick.

perlretut.

"Regexp Quote-Like Operators" in perlop.

"Gory details of parsing quoted constructs" in perlop.

perlfaq6.

"pos" in perlfunc.

perllocale.

perlebcdic.

Mastering Regular Expressions by Jeffrey Friedl, published by O'Reilly and Associates.


和訳 TRANSALTE TO JAPANESE

 山科 氷魚 (YAMASHINA Hio) <hio@hio.jp>

原典: perl VERSION 5.9.5. 翻訳日: 2007-08-14 Original distribution is perl VERSION 5.9.5. Translated on 2007-08-14.

perlre - Perl 正規表現
perlre - Perl regular expressions

索引 INDEX

perlre - Perl 正規表現
perlre - Perl regular expressions