5.12.1

名前

perlreref - Perl Regular Expressions Reference

perlreref - Perl の正規表現のリファレンス

説明

This is a quick reference to Perl's regular expressions. For full information see perlre and perlop, as well as the "SEE ALSO" section in this document.

本ドキュメントは、Perl の正規表現のクイックリファレンスです。 完全な情報は、perlreperlop、また、本ドキュメントの "SEE ALSO" セクションを参照してください。

演算子

=~ determines to which variable the regex is applied. In its absence, $_ is used.

=~ は正規表現が適用される変数を決定します。 省略された場合には、$_ が使われます。

    $var =~ /foo/;

!~ determines to which variable the regex is applied, and negates the result of the match; it returns false if the match succeeds, and true if it fails.

!~ は正規表現が適用される変数を決定し、マッチの結果を反転します; マッチが成功すれば偽を返し、失敗すれば真を返します。

    $var !~ /foo/;

m/pattern/msixpogc searches a string for a pattern match, applying the given options.

m/pattern/msixpogc パターンマッチのために文字列を検索し、 与えられたオプションを適用します。

    m  Multiline mode - ^ and $ match internal lines
    s  match as a Single line - . matches \n
    i  case-Insensitive
    x  eXtended legibility - free whitespace and comments
    p  Preserve a copy of the matched string -
       ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined.
    o  compile pattern Once
    g  Global - all occurrences
    c  don't reset pos on failed matches when using /g
    m  複数行モード - ^ と $ が内部的な行にマッチします
    s  単行としてマッチ - . が \n にマッチします
    i  大小文字の違いを無視します
    x  読みやすさの拡張 - 空白やコメントを自由に置けます
    p  マッチした文字列のコピーを保存する -
       ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} が定義されます。
    o  パターンを一度だけコンパイルします
    g  グローバル - マッチするものすべて
    c  /g を使っているときにマッチに失敗しても pos をリセットしません

If 'pattern' is an empty string, the last successfully matched regex is used. Delimiters other than '/' may be used for both this operator and the following ones. The leading m can be omitted if the delimiter is '/'.

'pattern' が空文字列なら、最後にマッチングに 成功した 正規表現が使われます。 この演算子とそれに続くものの両方で、'/' 以外のデリミタも使えます。 デリミタが '/' の場合は m は省略できます。

qr/pattern/msixpo lets you store a regex in a variable, or pass one around. Modifiers as for m//, and are stored within the regex.

qr/pattern/msixpo は、正規表現を変数に入れるか、順に回せるように します。 m// と同じ修飾子が使えて、正規表現に保管されます。

s/pattern/replacement/msixpogce substitutes matches of 'pattern' with 'replacement'. Modifiers as for m//, with one addition:

s/pattern/replacement/msixpogce は、'pattern' でマッチしたものを 'replacement' で置き換えます。 m// と同じ修飾子が使えて、さらに一つ追加されます:

    e  Evaluate 'replacement' as an expression
    e  'replacement' を式として評価します

'e' may be specified multiple times. 'replacement' is interpreted as a double quoted string unless a single-quote (') is the delimiter.

'e' は複数回指定できます。 'replacement' は、デリミタとしてシングルクォート (') が使われた場合を 除いて、ダブルクォートされた文字列として解釈されます。

?pattern? is like m/pattern/ but matches only once. No alternate delimiters can be used. Must be reset with reset().

?pattern?m/pattern/ に似ていますが、一度だけマッチします。 デリミタは変更できません。 reset() でリセットしなければなりません。

SYNTAX

   \       Escapes the character immediately following it
   .       Matches any single character except a newline (unless /s is used)
   ^       Matches at the beginning of the string (or line, if /m is used)
   $       Matches at the end of the string (or line, if /m is used)
   *       Matches the preceding element 0 or more times
   +       Matches the preceding element 1 or more times
   ?       Matches the preceding element 0 or 1 times
   {...}   Specifies a range of occurrences for the element preceding it
   [...]   Matches any one of the characters contained within the brackets
   (...)   Groups subexpressions for capturing to $1, $2...
   (?:...) Groups subexpressions without capturing (cluster)
   |       Matches either the subexpression preceding or following it
   \1, \2, \3 ...           Matches the text from the Nth group
   \g1 or \g{1}, \g2 ...    Matches the text from the Nth group
   \g-1 or \g{-1}, \g-2 ... Matches the text from the Nth previous group
   \g{name}     Named backreference
   \k<name>     Named backreference
   \k'name'     Named backreference
   (?P=name)    Named backreference (python syntax)
   \       直後の文字をエスケープします
   .       改行を除く任意の一文字にマッチします (/s が使われていない場合)
   ^       文字列(/m が使われている場合は行)の先頭にマッチします
   $       文字列(/m が使われている場合は行)の末尾にマッチします
   *       先行する要素のゼロ回以上の繰り返しにマッチします
   +       先行する要素の一回以上の繰り返しにマッチします
   ?       先行する要素のゼロ回または一回の出現にマッチします
   {...}   先行する要素の繰り返しの範囲を指定します
   [...]   ブラケットの内側にある文字のいずれかにマッチします
   (...)   $1, $2... のために部分正規表現をグループ化して捕捉します
   (?:...) 部分正規表現を捕捉することなくグループ化します (クラスター)
   |       左右いずれかにある部分正規表現にマッチします
   \1, \2, \3  ...          N 番目のグループのテキストにマッチします
   \g1 or \g{1}, \g2 ...    N 番目のグループのテキストにマッチします
   \g-1 or \g{-1}, \g-2 ... N 個前のグループのテキストにマッチします
   \g{name}     名前つき後方参照
   \k<name>     名前つき後方参照
   \k'name'     名前つき後方参照
   (?P=name)    名前つき後方参照 (python の文法)

エスケープシーケンス

These work as in normal strings.

これらは通常の文字列として働きます。

   \a       Alarm (beep)
   \e       Escape
   \f       Formfeed
   \n       Newline
   \r       Carriage return
   \t       Tab
   \037     Any octal ASCII value
   \x7f     Any hexadecimal ASCII value
   \x{263a} A wide hexadecimal value
   \cx      Control-x
   \N{name} A named character
   \N{U+263D} A Unicode character by hex ordinal
   \a       アラーム (ビープ)
   \e       エスケープ
   \f       改ページ
   \n       改行
   \r       キャリッジリターン
   \t       タブ
   \037     任意の 8 進 ASCII 値
   \x7f     任意の 16 進 ASCII 値
   \x{263a} ワイド 16 進値
   \cx      Control-x
   \N{name} 名前つき文字
   \N{U+263D} 16 進数による Unicode 文字
   \l  Lowercase next character
   \u  Titlecase next character
   \L  Lowercase until \E
   \U  Uppercase until \E
   \Q  Disable pattern metacharacters until \E
   \E  End modification
   \l  次の文字を小文字にします
   \u  次の文字をタイトル文字にします
   \L  \E まで小文字にします
   \U  \E まで大文字にします
   \Q  \E までパターンのメタ文字を無効にします
   \E  修正を終了します

For Titlecase, see "Titlecase".

タイトル文字にについては "Titlecase" を参照してください。

This one works differently from normal strings:

この 1 つは通常の文字列とは異なった働きをします:

   \b  An assertion, not backspace, except in a character class
   \b  文字クラスの中以外では、表明であってバックスペースではありません

文字クラス

   [amy]    Match 'a', 'm' or 'y'
   [f-j]    Dash specifies "range"
   [f-j-]   Dash escaped or at start or end means 'dash'
   [^f-j]   Caret indicates "match any character _except_ these"
   [amy]    'a', 'm', 'y' のいずれかにマッチ
   [f-j]    ダッシュは「範囲」を指定します
   [f-j-]   エスケープされるか、最初か最後にあるダッシュは「ダッシュ」を意味します
   [^f-j]   キャレットは「これら以外にマッチ」を示します

The following sequences (except \N) work within or without a character class. The first six are locale aware, all are Unicode aware. See perllocale and perlunicode for details.

(\N 以外の)以下のシーケンスは文字クラス内でもそれ以外でも動作します。 最初の 6 つはロケールの影響を受け、全ては Unicode の影響を受けます。 詳細については perllocaleperlunicode を参照してください。

   \d      A digit
   \D      A nondigit
   \w      A word character
   \W      A non-word character
   \s      A whitespace character
   \S      A non-whitespace character
   \h      An horizontal whitespace
   \H      A non horizontal whitespace
   \N      A non newline (when not followed by '{NAME}'; experimental; not
           valid in a character class; equivalent to [^\n]; it's like '.'
           without /s modifier)
   \v      A vertical whitespace
   \V      A non vertical whitespace
   \R      A generic newline           (?>\v|\x0D\x0A)
   \d      数値
   \D      非数値
   \w      単語文字
   \W      非単語文字
   \s      空白文字
   \S      非空白文字
   \h      水平空白文字
   \H      非水平空白文字
   \N      非改行 ('{NAME}' に引き続いていない場合; 実験的; 文字クラスでは
           不正; [^\n] と等価; /s なしの場合の '.' と同様)
   \v      垂直空白文字
   \V      非垂直空白文字
   \R      一般的な改行                (?>\v|\x0D\x0A)
   \C      Match a byte (with Unicode, '.' matches a character)
   \pP     Match P-named (Unicode) property
   \p{...} Match Unicode property with name longer than 1 character
   \PP     Match non-P
   \P{...} Match lack of Unicode property with name longer than 1 char
   \X      Match Unicode extended grapheme cluster
   \C      1 バイトにマッチする (Unicode では、'.' は文字にマッチする)
   \pP     P の名前の (Unicode) プロパティ
   \p{...} 1 文字より長い名前の Unicode プロパティにマッチする
   \PP     非 P にマッチする
   \P{...} 1 文字より長い名前の Unicode プロパティがないものにマッチする
   \X      Unicode の拡張書記素クラスタにマッチする

POSIX character classes and their Unicode and Perl equivalents:

POSIX 文字クラスと、それに対する Unicode と Perl の相当物は:

   alnum   IsAlnum              Alphanumeric
   alpha   IsAlpha              Alphabetic
   ascii   IsASCII              Any ASCII char
   blank   IsSpace  [ \t]       Horizontal whitespace (GNU extension)
   cntrl   IsCntrl              Control characters
   digit   IsDigit  \d          Digits
   graph   IsGraph              Alphanumeric and punctuation
   lower   IsLower              Lowercase chars (locale and Unicode aware)
   print   IsPrint              Alphanumeric, punct, and space
   punct   IsPunct              Punctuation
   space   IsSpace  [\s\ck]     Whitespace
           IsSpacePerl   \s     Perl's whitespace definition
   upper   IsUpper              Uppercase chars (locale and Unicode aware)
   word    IsWord   \w          Alphanumeric plus _ (Perl extension)
   xdigit  IsXDigit [0-9A-Fa-f] Hexadecimal digit
   alnum   IsAlnum              英数字
   alpha   IsAlpha              英字
   ascii   IsASCII              任意の ASCII 文字
   blank   IsSpace  [ \t]       水平空白 (GNU 拡張)
   cntrl   IsCntrl              制御文字
   digit   IsDigit  \d          数字
   graph   IsGraph              英数字と句読点
   lower   IsLower              小文字 (ロケールと Unicode の影響を受けます)
   print   IsPrint              英数字と句読点と空白
   punct   IsPunct              句読点
   space   IsSpace  [\s\ck]     空白
           IsSpacePerl   \s     Perl の空白の定義
   upper   IsUpper              大文字 (ロケールと Unicode の影響を受けます)
   word    IsWord   \w          英数字と _ (Perl 拡張)
   xdigit  IsXDigit [0-9A-Fa-f] 16 進数

Within a character class:

文字クラスの中では:

    POSIX       traditional   Unicode
    [:digit:]       \d        \p{IsDigit}
    [:^digit:]      \D        \P{IsDigit}
    POSIX         伝統的      Unicode
    [:digit:]       \d        \p{IsDigit}
    [:^digit:]      \D        \P{IsDigit}

アンカー

All are zero-width assertions.

すべてゼロ幅の表明です。

   ^  Match string start (or line, if /m is used)
   $  Match string end (or line, if /m is used) or before newline
   \b Match word boundary (between \w and \W)
   \B Match except at word boundary (between \w and \w or \W and \W)
   \A Match string start (regardless of /m)
   \Z Match string end (before optional newline)
   \z Match absolute string end
   \G Match where previous m//g left off
   ^  文字列(/m が指定されている場合には行)の先頭にマッチします
   $  文字列(/m が指定されている場合には行)の終端もしくは改行の前にマッチします
   \b 単語境界(\w と ¥W の間)にマッチします
   \B 単語境界以外(\w と \w の間か \W と \W の間)にマッチします
   \A 文字列の先頭(/m には影響されません)にマッチします
   \Z 文字列の末尾(省略可能な改行の前)にマッチします
   \z 文字列の本当の末尾にマッチします
   \G 前回の m//g のマッチした場所の末尾にマッチします
   \K Keep the stuff left of the \K, don't include it in $&
   \K \K の左側の内容を保存する; これは $& には含まれない

量指定子

Quantifiers are greedy by default and match the longest leftmost.

量指定子はデフォルトでは貪欲で、 一番左から 一番長く マッチします。

   Maximal Minimal Possessive Allowed range
   ------- ------- ---------- -------------
   {n,m}   {n,m}?  {n,m}+     Must occur at least n times
                              but no more than m times
   {n,}    {n,}?   {n,}+      Must occur at least n times
   {n}     {n}?    {n}+       Must occur exactly n times
   *       *?      *+         0 or more times (same as {0,})
   +       +?      ++         1 or more times (same as {1,})
   ?       ??      ?+         0 or 1 time (same as {0,1})
   最大    最小    所有格     範囲
   ------- ------- ---------- -------------
   {n,m}   {n,m}?  {n,m}+     最低 n 回、m 回以内出現
   {n,}    {n,}?   {n,}+      最低 n 回出現
   {n}     {n}?    {n}+       正確に n 回出現
   *       *?      *+         0 回以上 ({0,} と同じ)
   +       +?      ++         1 回以上 ({1,} と同じ)
   ?       ??      ?+         0 回または 1 回 ({0,1} と同じ)

The possessive forms (new in Perl 5.10) prevent backtracking: what gets matched by a pattern with a possessive quantifier will not be backtracked into, even if that causes the whole match to fail.

(Perl 5.10 で導入された) 所有格はバックトラックを抑制します: 所有格量指定子が付いたパターンでマッチした場合、バックトラックはしません; たとえこれによってマッチ全体が失敗することになってもです。

There is no quantifier {,n}. That's interpreted as a literal string.

{,n} という量指定子はありません。 これはリテラルな文字列として扱われます。

拡張構造

   (?#text)          A comment
   (?:...)           Groups subexpressions without capturing (cluster)
   (?pimsx-imsx:...) Enable/disable option (as per m// modifiers)
   (?=...)           Zero-width positive lookahead assertion
   (?!...)           Zero-width negative lookahead assertion
   (?<=...)          Zero-width positive lookbehind assertion
   (?<!...)          Zero-width negative lookbehind assertion
   (?>...)           Grab what we can, prohibit backtracking
   (?|...)           Branch reset
   (?<name>...)      Named capture
   (?'name'...)      Named capture
   (?P<name>...)     Named capture (python syntax)
   (?{ code })       Embedded code, return value becomes $^R
   (??{ code })      Dynamic regex, return value used as regex
   (?N)              Recurse into subpattern number N
   (?-N), (?+N)      Recurse into Nth previous/next subpattern
   (?R), (?0)        Recurse at the beginning of the whole pattern
   (?&name)          Recurse into a named subpattern
   (?P>name)         Recurse into a named subpattern (python syntax)
   (?(cond)yes|no)
   (?(cond)yes)      Conditional expression, where "cond" can be:
                     (N)       subpattern N has matched something
                     (<name>)  named subpattern has matched something
                     ('name')  named subpattern has matched something
                     (?{code}) code condition
                     (R)       true if recursing
                     (RN)      true if recursing into Nth subpattern
                     (R&name)  true if recursing into named subpattern
                     (DEFINE)  always false, no no-pattern allowed
   (?#text)          コメント
   (?:...)           部分正規表現を捕捉することなくグループ化します (クラスター)
   (?imxs-imsx:...)  オプションを有効/無効にする (m// 修飾子のものと同じ)
   (?=...)           ゼロ幅の肯定先読み表明
   (?!...)           ゼロ幅の否定先読み表明
   (?<=...)          ゼロ幅の肯定後読み表明
   (?<!...)          ゼロ幅の否定後読み表明
   (?>...)           出来うる限りマッチし、バックトラックしない
   (?|...)           分岐のリセット
   (?<name>...)      名前付き捕捉
   (?'name'...)      名前付き捕捉
   (?P<name>...)     名前付き捕捉 (python 文法)
   (?{ code })       埋め込みコード。 戻り値は $^R に格納されます
   (??{ code })      動的正規表現。戻り値は正規表現として扱われます
   (?N)              サブパターン番号 N に再帰する
   (?-N), (?+N)      N 個前/後のサブパターンに再帰する
   (?R), (?0)        パターン全体の先頭に再帰する
   (?&name)          名前付きサブパターンに再帰する
   (?P>name)         名前付きサブパターンに再帰する (python 文法)
   (?(cond)yes|no)
   (?(cond)yes)      条件式; "cond" で指定できるのは:
                     (N)       サブパターン N が何かにマッチした
                     (<name>)  名前付きサブルーチンが何かにマッチした
                     ('name')  名前付きサブルーチンが何かにマッチした
                     (?{code}) コード条件
                     (R)       再帰したら真
                     (RN)      N 番目のサブパターンに再帰したら真
                     (R&name)  名前付きサブパターンに再帰したら真
                     (DEFINE)  常に偽; パターンなしは許されない

変数

   $_    Default variable for operators to use
   $_    演算子が使用するデフォルトの変数
   $`    Everything prior to matched string
   $&    Entire matched string
   $'    Everything after to matched string
   $`    マッチした文字列に先行する部分
   $&    マッチした文字列全体
   $'    マッチした文字列に後続する部分
   ${^PREMATCH}   Everything prior to matched string
   ${^MATCH}      Entire matched string
   ${^POSTMATCH}  Everything after to matched string
   ${^PREMATCH}   マッチした文字列に先行する部分
   ${^MATCH}      マッチした文字列全体
   ${^POSTMATCH}  マッチした文字列に後続する部分

The use of $`, $& or $' will slow down all regex use within your program. Consult perlvar for @- to see equivalent expressions that won't cause slow down. See also Devel::SawAmpersand. Starting with Perl 5.10, you can also use the equivalent variables ${^PREMATCH}, ${^MATCH} and ${^POSTMATCH}, but for them to be defined, you have to specify the /p (preserve) modifier on your regular expression.

$`, $&, $' のいずれかを使うと、プログラム中の 全ての 正規表現の 速度が低下します。 速度低下を引き起こさない、等価な表現のためには、perlvar@- を 調べてみてください。 また、Devel::SawAmpersand も参照してください。 Perl 5.10 から、等価な変数である ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} も使えますが、これらが定義されるには、正規表現に /p (保存(preserve)) 修飾子をつける必要があります。

   $1, $2 ...  hold the Xth captured expr
   $+    Last parenthesized pattern match
   $^N   Holds the most recently closed capture
   $^R   Holds the result of the last (?{...}) expr
   @-    Offsets of starts of groups. $-[0] holds start of whole match
   @+    Offsets of ends of groups. $+[0] holds end of whole match
   %+    Named capture buffers
   %-    Named capture buffers, as array refs
   $1, $2 ...  X 番目の捕捉された式を保持します
   $+    最後にかっこで囲まれたパターンマッチ
   $^N   最も近くに閉じた捕捉を保持します
   $^R   最後の (?{...}) 式の結果を保持します
   @-    グループの先頭からのオフセット; $-[0] はマッチ全体の先頭です
   @+    グループの末尾からのオフセット; $+[0] はマッチ全体の末尾です
   %+    名前付き捕捉バッファ
   %-    配列リファレンスとしての名前付き捕捉バッファ

Captured groups are numbered according to their opening paren.

捕捉したグループは 開き かっこの順番で番号付けされます。

関数

   lc          Lowercase a string
   lcfirst     Lowercase first char of a string
   uc          Uppercase a string
   ucfirst     Titlecase first char of a string
   lc          文字列を小文字にします
   lcfirst     文字列の最初の文字を小文字にします
   uc          文字列を大文字にします
   ucfirst     文字列の最初の文字を Titlecase にします
   pos         Return or set current match position
   quotemeta   Quote metacharacters
   reset       Reset ?pattern? status
   study       Analyze string for optimizing matching
   pos         カレントのマッチ位置を返したり設定したりします
   quotemeta   メタ文字をクォートします
   reset       ?pattern? の状態をリセットします
   study       マッチングの最適化のために文字列を調べます
   split       Use a regex to split a string into parts
   split       文字列を分割するために正規表現を使います

The first four of these are like the escape sequences \L, \l, \U, and \u. For Titlecase, see "Titlecase".

これらの最初の 4 つは、エスケープシーケンス \L, \l, \U, \u と 似ています。 タイトル文字については、"Titlecase" を参照してください。

用語

タイトル文字

Unicode concept which most often is equal to uppercase, but for certain characters like the German "sharp s" there is a difference.

Unicode の概念で、ほとんどの場合は大文字と同じですが、ドイツ語の "sharp s" のような特定の文字については異なります。

作者

Iain Truskett. Updated by the Perl 5 Porters.

This document may be distributed under the same terms as Perl itself.

SEE ALSO

  • perlretut for a tutorial on regular expressions.

    正規表現のチュートリアルである perlretut

  • perlrequick for a rapid tutorial.

    手っ取り早いチュートリアルである perlrequick

  • perlre for more details.

    さらなる詳細である perlre

  • perlvar for details on the variables.

    変数に関する詳細である perlvar

  • perlop for details on the operators.

    演算子の詳細である perlop

  • perlfunc for details on the functions.

    関数の詳細である perlfunc

  • perlfaq6 for FAQs on regular expressions.

    正規表現に関する FAQ である perlfaq6

  • perlrebackslash for a reference on backslash sequences.

    バックスラッシュシーケンス の参考資料である perlrebackslash

  • perlrecharclass for a reference on character classes.

    文字クラスの参考資料である perlrecharclass

  • The re module to alter behaviour and aid debugging.

    振る舞いの変更とデバッグの補助のための re モジュール。

  • "Debugging regular expressions" in perldebug

  • perluniintro, perlunicode, charnames and perllocale for details on regexes and internationalisation.

    正規表現や国際化に関する詳細である perluniintro, perlunicode, charnames, perllocale

  • Mastering Regular Expressions by Jeffrey Friedl (http://oreilly.com/catalog/9780596528126/) for a thorough grounding and reference on the topic.

    この話題に関する完全な背景と参考資料である Jeffrey Friedl による書籍 Mastering Regular Expressions (http://oreilly.com/catalog/9780596528126/) (O'Reillyから出版。 ISBN 1556592-257-3)。 日本語版は「詳説 正規表現」ISBN4-87311-130-7 (第二版のもの)。

THANKS

David P.C. Wollmann, Richard Soderberg, Sean M. Burke, Tom Christiansen, Jim Cromie, and Jeffrey Goff for useful advice.