5.38.0

名前

perlrequick - Perl regular expressions quick start

perlrequick - Perl 正規表現のクイックスタート

説明

This page covers the very basics of understanding, creating and using regular expressions ('regexes') in Perl.

このページは、Perl の正規表現 ('regexes') の理解、作成、使用の基本中の 基本に対応しています。

ガイド

This page assumes you already know things, like what a "pattern" is, and the basic syntax of using them. If you don't, see perlretut.

このページは、あなたが「パターンとは何か」やそれを使うための基本的な 文法を既に知っていることを仮定しています。 もしそうでなければ、perlretut を参照してください。

単純な単語のマッチング

The simplest regex is simply a word, or more generally, a string of characters. A regex consisting of a word matches any string that contains that word:

最も単純な正規表現は単なる単語、より一般的には文字の並びです。 正規表現は単語を構成する任意の文字列にマッチングする単語からなります:

    "Hello World" =~ /World/;  # matches

In this statement, World is a regex and the // enclosing /World/ tells Perl to search a string for a match. The operator =~ associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match. In our case, World matches the second word in "Hello World", so the expression is true. This idea has several variations.

この文で、World は正規表現であり、 // で囲まれた /World/ は Perl に対してマッチングのために文字列を検索することを指示します。 =~ という演算子は正規表現にマッチングする文字列に結び付けられ、 正規表現がマッチングすれば真の値を生成し、マッチングしなければ偽となります。 この例では、World"Hello World" の二番目の単語にマッチングするので、 式は真となります。 この考え方にはいくつかのバリエーションがあります。

Expressions like this are useful in conditionals:

以下のような式は条件文で便利です:

    print "It matches\n" if "Hello World" =~ /World/;

The sense of the match can be reversed by using !~ operator:

マッチングの成否の意味を反転する演算子 !~ があります:

    print "It doesn't match\n" if "Hello World" !~ /World/;

The literal string in the regex can be replaced by a variable:

正規表現中のリテラル文字列は変数に置き換えることもができます:

    $greeting = "World";
    print "It matches\n" if "Hello World" =~ /$greeting/;

If you're matching against $_, the $_ =~ part can be omitted:

$_ に対してマッチングを行う場合、$_ =~ の部分は省略できます:

    $_ = "Hello World";
    print "It matches\n" if /World/;

Finally, the // default delimiters for a match can be changed to arbitrary delimiters by putting an 'm' out front:

最後に、マッチングのための // のデフォルトデリミタは 'm' を 前置することにより任意のものにすることができます:

    "Hello World" =~ m!World!;   # matches, delimited by '!'
    "Hello World" =~ m{World};   # matches, note the matching '{}'
    "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
                                 # '/' becomes an ordinary char
    "Hello World" =~ m!World!;   # マッチングする; デリミタは '!'
    "Hello World" =~ m{World};   # マッチングする; 組になっている '{}' に注意
    "/usr/bin/perl" =~ m"/perl"; # 'usr/bin' の後にマッチングする
                                 # '/' は普通の文字になっている

Regexes must match a part of the string exactly in order for the statement to be true:

正規表現は、文が真となるためには 正確に 順序通りに文字列の 一部としてマッチングしなければなりません。

    "Hello World" =~ /world/;  # doesn't match, case sensitive
    "Hello World" =~ /o W/;    # matches, ' ' is an ordinary char
    "Hello World" =~ /World /; # doesn't match, no ' ' at end
    "Hello World" =~ /world/;  # マッチングしない; 大文字小文字は区別する
    "Hello World" =~ /o W/;    # マッチングする; ' ' は普通の文字
    "Hello World" =~ /World /; # マッチングしない; 末尾に ' ' はない

Perl will always match at the earliest possible point in the string:

Perl は常に文字列の中で最初に現れるものをマッチングしようとします:

    "Hello World" =~ /o/;       # matches 'o' in 'Hello'
    "That hat is red" =~ /hat/; # matches 'hat' in 'That'
    "Hello World" =~ /o/;       # 'Hello' の 'o' にマッチング
    "That hat is red" =~ /hat/; # 'That' の中の 'hat' にマッチング

Not all characters can be used 'as is' in a match. Some characters, called metacharacters, are considered special, and reserved for use in regex notation. The metacharacters are

すべての文字がマッチングにおいて'あるがまま'(as is) に使われるのでは ありません。 メタ文字 と呼ばれるいくつかの文字は特別であると考えられ、 正規表現の記述に使うために予約されています。 メタ文字には以下のものがあります

    {}[]()^$.|*+?\

A metacharacter can be matched literally by putting a backslash before it:

メタ文字はバックスラッシュを前置することによってリテラルに マッチングさせられます:

    "2+2=4" =~ /2+2/;    # doesn't match, + is a metacharacter
    "2+2=4" =~ /2\+2/;   # matches, \+ is treated like an ordinary +
    'C:\WIN32' =~ /C:\\WIN/;                       # matches
    "/usr/bin/perl" =~ /\/usr\/bin\/perl/;  # matches
    "2+2=4" =~ /2+2/;    # マッチングしない; + はメタ文字
    "2+2=4" =~ /2\+2/;   # マッチングする; \+ 普通の + のように扱われる
    'C:\WIN32' =~ /C:\\WIN/;                       # マッチングする
    "/usr/bin/perl" =~ /\/usr\/bin\/perl/;  # マッチングする

In the last regex, the forward slash '/' is also backslashed, because it is used to delimit the regex.

最後の正規表現では、スラッシュ '/' もまたバックスラッシュが つけられています; なぜなら、それが正規表現のデリミタとして使われているからです。

Most of the metacharacters aren't always special, and other characters (such as the ones delimiting the pattern) become special under various circumstances. This can be confusing and lead to unexpected results. use re 'strict' can notify you of potential pitfalls.

ほとんどのメタ文字は常に特別ではなく、 (パターンを区切るような) その他の文字は様々な条件で特別になります。 これは分かりにくく、想定外の結果を引き起こすかも知れません。 use re 'strict' は、潜在的な落とし穴を あなたに通知します。

Non-printable ASCII characters are represented by escape sequences. Common examples are \t for a tab, \n for a newline, and \r for a carriage return. Arbitrary bytes are represented by octal escape sequences, e.g., \033, or hexadecimal escape sequences, e.g., \x1B:

印字できない ASCII 文字は エスケープシーケンス によって表現されます。 一般的な例では、タブを表す \t、改行を表す \n、復帰を表す \r が あります。 任意のバイトは 8 進エスケープシーケンス (例えば \033) あるいは 16 進エスケープシーケンス (例えば \x1B) で表現できます:

    "1000\t2000" =~ m(0\t2)  # matches
    "cat" =~ /\143\x61\x74/  # matches in ASCII, but
                             # a weird way to spell cat
    "1000\t2000" =~ m(0\t2)  # マッチングする
    "cat" =~ /\143\x61\x74/  # ASCII でマッチングするが、
                             # cat を綴る変な方法

Regexes are treated mostly as double-quoted strings, so variable substitution works:

正規表現はほとんどの場合においてダブルクォートで囲まれた文字列のように 扱われるので、変数置換は動作します:

    $foo = 'house';
    'cathouse' =~ /cat$foo/;   # matches
    'housecat' =~ /${foo}cat/; # matches
    $foo = 'house';
    'cathouse' =~ /cat$foo/;   # マッチングする
    'housecat' =~ /${foo}cat/; # マッチングする

With all of the regexes above, if the regex matched anywhere in the string, it was considered a match. To specify where it should match, we would use the anchor metacharacters ^ and $. The anchor ^ means match at the beginning of the string and the anchor $ means match at the end of the string, or before a newline at the end of the string. Some examples:

これまでの正規表現では、文字列のどこかでマッチングすればマッチングしたと みなしてきました。 文字列の どこで 正規表現がマッチングするのかを指定するには、 アンカー メタ文字である ^$ を使います。 アンカー ^ は文字列の先頭でマッチングすることを意味し、アンカー $ は 文字列の末尾(あるいは文字列の末尾にある改行の前) でマッチングすることを 意味します。 いくつか例を挙げます:

    "housekeeper" =~ /keeper/;         # matches
    "housekeeper" =~ /^keeper/;        # doesn't match
    "housekeeper" =~ /keeper$/;        # matches
    "housekeeper\n" =~ /keeper$/;      # matches
    "housekeeper" =~ /^housekeeper$/;  # matches
    "housekeeper" =~ /keeper/;         # マッチングする
    "housekeeper" =~ /^keeper/;        # マッチングしない
    "housekeeper" =~ /keeper$/;        # マッチングする
    "housekeeper\n" =~ /keeper$/;      # マッチングする
    "housekeeper" =~ /^housekeeper$/;  # マッチングする

文字クラスを使う

A character class allows a set of possible characters, rather than just a single character, to match at a particular point in a regex. There are a number of different types of character classes, but usually when people use this term, they are referring to the type described in this section, which are technically called "Bracketed character classes", because they are denoted by brackets [...], with the set of characters to be possibly matched inside. But we'll drop the "bracketed" below to correspond with common usage. Here are some examples of (bracketed) character classes:

文字クラス は正規表現の特定の場所においてマッチングする可能性のある文字の 集合です(単一の文字ではありません)。 文字クラスには様々な種類がありますが、通常人々がこの用語を使うときは、 彼らは技術的には(大かっこ [...] で表現され、マッチングする 可能性のある文字の集合がその内側に置かれるので) 「大かっこ文字クラス」と呼ばれる、この章で記述される種類を参照しています。 しかし一般的な使い方に対応するために以下では「大かっこ」を省略します。 以下は(大かっこ)文字クラスの例です:

    /cat/;            # matches 'cat'
    /[bcr]at/;        # matches 'bat', 'cat', or 'rat'
    "abc" =~ /[cab]/; # matches 'a'
    /cat/;            # 'cat' にマッチングする
    /[bcr]at/;        # 'bat', 'cat', 'rat' のいずれかにマッチングする
    "abc" =~ /[cab]/; # 'a' にマッチングする

In the last statement, even though 'c' is the first character in the class, the earliest point at which the regex can match is 'a'.

最後の文において、'c' がクラスの最初の文字であるにもかかわらず 正規表現がマッチングすることのできる最初の位置にある文字である 'a' が マッチングします。

    /[yY][eE][sS]/; # match 'yes' in a case-insensitive way
                    # 'yes', 'Yes', 'YES', etc.
    /yes/i;         # also match 'yes' in a case-insensitive way
    /[yY][eE][sS]/; # 大文字小文字を無視して 'yes' にマッチングする
                    # 'yes', 'Yes', 'YES' など。
    /yes/i;         # これも大文字小文字を無視して 'yes' にマッチングする

The last example shows a match with an 'i' modifier, which makes the match case-insensitive.

最後の例は大文字小文字を無視してマッチングするようにする 'i' 修飾子 (modifier) を使ったマッチングを示しています。

Character classes also have ordinary and special characters, but the sets of ordinary and special characters inside a character class are different than those outside a character class. The special characters for a character class are -]\^$ and are matched using an escape:

文字クラスも普通の文字と特殊文字がありますが、文字クラスの内側での 普通の文字と特殊文字は、文字クラスの外側の物とは違います。 文字クラスのために特殊な文字は -]\^$ で、エスケープを使って マッチングされます:

   /[\]c]def/; # matches ']def' or 'cdef'
   $x = 'bcr';
   /[$x]at/;   # matches 'bat, 'cat', or 'rat'
   /[\$x]at/;  # matches '$at' or 'xat'
   /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'
   /[\]c]def/; # ']def' または 'cdef' にマッチング
   $x = 'bcr';
   /[$x]at/;   # 'bat', 'cat', 'rat' にマッチング
   /[\$x]at/;  # '$at' または 'xat' にマッチング
   /[\\$x]at/; # '\at', 'bat, 'cat', 'rat' にマッチング

The special character '-' acts as a range operator within character classes, so that the unwieldy [0123456789] and [abc...xyz] become the svelte [0-9] and [a-z]:

特殊文字 '-' は文字クラスの中で範囲演算子として振舞うので、 [0123456789][abc...xyz] のような 見づらいものはすっきりとした [0-9] であるとか [a-z] のように 書き換えられます:

    /item[0-9]/;  # matches 'item0' or ... or 'item9'
    /[0-9a-fA-F]/;  # matches a hexadecimal digit
    /item[0-9]/;  # 'item0' ... 'item9' にマッチングする
    /[0-9a-fA-F]/;  # 16 進数にマッチングする

If '-' is the first or last character in a character class, it is treated as an ordinary character.

'-' が文字クラスの中の最初か最後の文字であった場合、通常の文字として 扱われます。

The special character ^ in the first position of a character class denotes a negated character class, which matches any character but those in the brackets. Both [...] and [^...] must match a character, or the match fails. Then

文字クラスの先頭の位置にある特殊文字 ^反転文字クラス を表し、 ブラケットの中にない文字にマッチングします。 [...][^...] の両方とも、一つの文字にマッチングせねばならず、 そうでない場合にはマッチングは失敗します。 ですから

    /[^a]at/;  # doesn't match 'aat' or 'at', but matches
               # all other 'bat', 'cat, '0at', '%at', etc.
    /[^0-9]/;  # matches a non-numeric character
    /[a^]at/;  # matches 'aat' or '^at'; here '^' is ordinary
    /[^a]at/;  # 'aat' や 'at' にはマッチングしないが、その他の
               # 'bat', 'cat, '0at', '%at' などにはマッチングする
    /[^0-9]/;  # 数字以外にマッチングする
    /[a^]at/;  # 'aat' か '^at'にマッチングする; ここでは '^' は通常の文字

Perl has several abbreviations for common character classes. (These definitions are those that Perl uses in ASCII-safe mode with the /a modifier. Otherwise they could match many more non-ASCII Unicode characters as well. See "Backslash sequences" in perlrecharclass for details.)

Perl は一般的な文字クラスの略記法を持っています。 (これらの定義は Perl が /a 修飾子によって ASCII 安全モードを 使っているときのものです。 さもなければもっと多くの非 ASCII の Unicode 文字に マッチングするかもしれません。 詳しくは "Backslash sequences" in perlrecharclass を参照してください。)

  • \d is a digit and represents

    \d は数字で、以下のものを表します

        [0-9]
  • \s is a whitespace character and represents

    \s は空白文字で、以下のものを表します

        [\ \t\r\n\f]
  • \w is a word character (alphanumeric or _) and represents

    \w は単語を構成する文字(英数字 と _)で、以下のものを表します

        [0-9a-zA-Z_]
  • \D is a negated \d; it represents any character but a digit

    \D は \d の否定形です; 数字以外の文字を表します

        [^0-9]
  • \S is a negated \s; it represents any non-whitespace character

    \S は \s の否定形です; 非空白文字を表します

        [^\s]
  • \W is a negated \w; it represents any non-word character

    \W は \w の否定形です; 単語を構成しない文字を表します

        [^\w]
  • The period '.' matches any character but "\n"

    ピリオド '.' は "\n" 以外の任意の文字にマッチングします

The \d\s\w\D\S\W abbreviations can be used both inside and outside of character classes. Here are some in use:

\d\s\w\D\S\W の省略記法は文字クラスの内側でも外側でも使うことができます。 以下はその例です:

    /\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format
    /[\d\s]/;         # matches any digit or whitespace character
    /\w\W\w/;         # matches a word char, followed by a
                      # non-word char, followed by a word char
    /..rt/;           # matches any two chars, followed by 'rt'
    /end\./;          # matches 'end.'
    /end[.]/;         # same thing, matches 'end.'
    /\d\d:\d\d:\d\d/; # hh:mm:ss 形式の時間表記にマッチング
    /[\d\s]/;         # 数字または空白にマッチング
    /\w\W\w/;         # 非単語文字が続きさらに単語文字が続く
                      # 単語文字にマッチング
    /..rt/;           # 'rt' が続く任意の二文字にマッチング
    /end\./;          # 'end.' にマッチング
    /end[.]/;         # 同じこと; 'end.' にマッチング

The word anchor \b matches a boundary between a word character and a non-word character \w\W or \W\w:

語アンカー (word anchor) \b はこれは単語を構成する文字と単語を 構成しない文字の間 \w\W\W\w の境界にマッチングします:

    $x = "Housecat catenates house and cat";
    $x =~ /\bcat/;  # matches cat in 'catenates'
    $x =~ /cat\b/;  # matches cat in 'housecat'
    $x =~ /\bcat\b/;  # matches 'cat' at end of string
    $x = "Housecat catenates house and cat";
    $x =~ /cat/;    # 'housecat' の cat にマッチング
    $x =~ /\bcat/;  # 'catenates' の cat にマッチング
    $x =~ /cat\b/;  # 'housecat' の cat にマッチング
    $x =~ /\bcat\b/;  # 文字列の終端の'cat'にマッチング

In the last example, the end of the string is considered a word boundary.

最後の例では、文字列の終端は単語境界として認識されています。

For natural language processing (so that, for example, apostrophes are included in words), use instead \b{wb}

自然言語処理 (つまり、例えば、アポストロティが単語に含まれているような) で使う場合は、代わりに \b{wb} を使ってください:

    "don't" =~ / .+? \b{wb} /x;  # matches the whole string

    "don't" =~ / .+? \b{wb} /x;  # matches the whole string

あれやこれやにマッチングする

We can match different character strings with the alternation metacharacter '|'. To match dog or cat, we form the regex dog|cat. As before, Perl will try to match the regex at the earliest possible point in the string. At each character position, Perl will first try to match the first alternative, dog. If dog doesn't match, Perl will then try the next alternative, cat. If cat doesn't match either, then the match fails and Perl moves to the next position in the string. Some examples:

異なる文字列を 選択 メタ文字 '|' によって行えます。 dog または cat にマッチングさせるには、正規表現を dog|cat のようにします。 以前述べた通り、Perlは文字列の可能な限り最も早い位置でマッチングを 行おうとします。 それぞれの文字位置で、Perlはまずはじめに最初の選択である dog に マッチングさせることを試みます。 もし dog がマッチングしなければ、Perl は次の選択肢である cat を 試します。 cat もまたマッチングしなければ、マッチングは失敗してPerlは文字列の 次の位置に移動します。 いくつか例を挙げます:

    "cats and dogs" =~ /cat|dog|bird/;  # matches "cat"
    "cats and dogs" =~ /dog|cat|bird/;  # matches "cat"
    "cats and dogs" =~ /cat|dog|bird/;  # "cat" にマッチング
    "cats and dogs" =~ /dog|cat|bird/;  # "cat" にマッチング

Even though dog is the first alternative in the second regex, cat is able to match earlier in the string.

二番目の正規表現において最初の選択肢が dog であるにもかかわらず、 cat が文字列で最初に現れるマッチング対象です。

    "cats"          =~ /c|ca|cat|cats/; # matches "c"
    "cats"          =~ /cats|cat|ca|c/; # matches "cats"
    "cats"          =~ /c|ca|cat|cats/; # "c" にマッチング
    "cats"          =~ /cats|cat|ca|c/; # "cats" にマッチング

At a given character position, the first alternative that allows the regex match to succeed will be the one that matches. Here, all the alternatives match at the first string position, so the first matches.

与えられた文字位置で、正規表現のマッチングを成功させるための 最初の選択肢はマッチングする一つとなります。 ここでは、全ての選択はは最初の文字列位置でマッチングするので、 最初のものがマッチングします。

グループ化と階層的マッチング

The grouping metacharacters () allow a part of a regex to be treated as a single unit. Parts of a regex are grouped by enclosing them in parentheses. The regex house(cat|keeper) means match house followed by either cat or keeper. Some more examples are

グループ化 メタ文字 () は正規表現の一部分を一つのユニットとして 扱うことを許します。 ある正規表現の一部はカッコによって囲まれることでグループ化されます。 正規表現 house(cat|keeper) は、catkeeper が後続する house にマッチングすることを意味します。 幾つか例を挙げましょう

    /(a|b)b/;    # matches 'ab' or 'bb'
    /(^a|b)c/;   # matches 'ac' at start of string or 'bc' anywhere
    /(a|b)b/;    # 'ab' または 'bb' にマッチング
    /(^a|b)c/;   # 文字列の先頭にある 'ac' か任意の場所の'bc'にマッチング
    /house(cat|)/;  # matches either 'housecat' or 'house'
    /house(cat(s|)|)/;  # matches either 'housecats' or 'housecat' or
                        # 'house'.  Note groups can be nested.
    /house(cat|)/;  # 'housecat' か 'house' にマッチング
    /house(cat(s|)|)/;  # 'housecats' か 'housecat' か 'house' のいずれかに
                        # マッチング。グループがネストできることに注意
    "20" =~ /(19|20|)\d\d/;  # matches the null alternative '()\d\d',
                             # because '20\d\d' can't match
    "20" =~ /(19|20|)\d\d/;  # 空の選択肢 '()\d\d' にマッチング
                             # '20\d\d' はマッチングできないから

マッチングしたものを取り出す

The grouping metacharacters () also allow the extraction of the parts of a string that matched. For each grouping, the part that matched inside goes into the special variables $1, $2, etc. They can be used just as ordinary variables:

グループ化メタ文字 () はまた、マッチングした文字列の一部分を 展開することができます。 それぞれのグループ化に対して、マッチングした部分が特殊変数 $1, $2 などに格納されます。 これらの変数は通常の変数と同じように使うことができます:

    # extract hours, minutes, seconds
    $time =~ /(\d\d):(\d\d):(\d\d)/;  # match hh:mm:ss format
    $hours = $1;
    $minutes = $2;
    $seconds = $3;
    # 時、分、秒を抽出する
    $time =~ /(\d\d):(\d\d):(\d\d)/;  # hh:mm:ss 形式にマッチングする
    $hours = $1;
    $minutes = $2;
    $seconds = $3;

In list context, a match /regex/ with groupings will return the list of matched values ($1,$2,...). So we could rewrite it as

リストコンテキストでは、グループ化付きのマッチング /regex/ は マッチングした値のリスト ($1,$2,...) を返します。 従ってこれは以下のように書き換えられます

    ($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);

If the groupings in a regex are nested, $1 gets the group with the leftmost opening parenthesis, $2 the next opening parenthesis, etc. For example, here is a complex regex and the matching variables indicated below it:

正規表現中のグループ化がネストしていた場合、$1 は最も左にある 開きかっこによってグループ化されているものを取り、$2 は 次の開きかっこによるものを取り…となっていきます。 例えば、以下は複雑な正規表現と、後述するマッチング変数です:

    /(ab(cd|ef)((gi)|j))/;
     1  2      34

Associated with the matching variables $1, $2, ... are the backreferences \g1, \g2, ... Backreferences are matching variables that can be used inside a regex:

マッチング変数 $1, $2 …に密接に結び付けられたものは、 後方参照 (backreferences) \g1, \g2 …です。 後方参照は正規表現の 内側 で使うことのできるマッチング変数です:

    /(\w\w\w)\s\g1/; # find sequences like 'the the' in string
    /(\w\w\w)\s\g1/; # 文字列中の 'the the' のような並びを探す

$1, $2, ... should only be used outside of a regex, and \g1, \g2, ... only inside a regex.

$1, $2 …は正規表現の外側のみで用い、 後方参照 \g1, \g2 …は正規表現の内側でのみ使うようにすべきです。

マッチングの繰り返し

The quantifier metacharacters ?, *, +, and {} allow us to determine the number of repeats of a portion of a regex we consider to be a match. Quantifiers are put immediately after the character, character class, or grouping that we want to specify. They have the following meanings:

量指定子 (quantifier) ?, *, +, {} によって、 マッチングさせたいと考えている正規表現の一部分の繰り返し回数を 指定できます。 量指定子は繰り返しを指定したい文字、文字クラス、またはグループの直後に 置きます。 量指定子には以下のような意味があります:

  • a? = match 'a' 1 or 0 times

    a? は: 'a' または空文字列にマッチングします。

  • a* = match 'a' 0 or more times, i.e., any number of times

    a* は: 'a' のゼロ回以上の繰り返しにマッチングします。

  • a+ = match 'a' 1 or more times, i.e., at least once

    a+ は: 'a' の一回以上の繰り返しにマッチングします。

  • a{n,m} = match at least n times, but not more than m times.

    a{n,m} は: n 回以上 m 回以下の繰り返しにマッチングします。

  • a{n,} = match at least n or more times

    a{n,} は: n 回以上の繰り返しにマッチングします。

  • a{,n} = match n times or fewer

    a{,n} は: n 回以下の繰り返しにマッチングします。

  • a{n} = match exactly n times

    a{n} は: n 回の繰り返しにマッチングします。

Here are some examples:

以下に幾つか例を挙げます:

    /[a-z]+\s+\d*/;  # match a lowercase word, at least some space, and
                     # any number of digits
    /(\w+)\s+\g1/;    # match doubled words of arbitrary length
    $year =~ /^\d{2,4}$/;  # make sure year is at least 2 but not more
                           # than 4 digits
    $year =~ /^\d{ 4 }$|^\d{2}$/; # better match; throw out 3 digit dates
    /[a-z]+\s+\d*/;  # 小文字の単語、幾つかの空白、それに続く任意の長さの
                     # 数字にマッチング
    /(\w+)\s+\1/;     # 任意の長さの単語の重複にマッチング
    $year =~ /\d{2,4}/;  # 年が少なくとも 2 桁あるが最大でも 4 桁に
                         # なるようにする
    $year =~ /^\d{ 4 }$|^\d{2}$/; # もっと良い; 3 桁をはじく

These quantifiers will try to match as much of the string as possible, while still allowing the regex to match. So we have

これらの量指定子はは正規表現のマッチングが成功するのを許す範囲で 可能な限りの文字列をマッチングさせようとします。 従って、以下のようになります

    $x = 'the cat in the hat';
    $x =~ /^(.*)(at)(.*)$/; # matches,
                            # $1 = 'the cat in the h'
                            # $2 = 'at'
                            # $3 = ''   (0 matches)
    $x = 'the cat in the hat';
    $x =~ /^(.*)(at)(.*)$/; # マッチングする
                            # $1 = 'the cat in the h'
                            # $2 = 'at'
                            # $3 = ''   (0 回マッチング)

The first quantifier .* grabs as much of the string as possible while still having the regex match. The second quantifier .* has no string left to it, so it matches 0 times.

最初の量指定子 .* は正規表現がマッチングする範囲で可能な限りの 長い文字列をつかみとります。 2 番目の量指定子は .* には文字列が残されていないので、0 回 マッチングします。

更なるマッチング

There are a few more things you might want to know about matching operators. The global modifier /g allows the matching operator to match within a string as many times as possible. In scalar context, successive matches against a string will have /g jump from match to match, keeping track of position in the string as it goes along. You can get or set the position with the pos() function. For example,

マッチング演算子について知りたいかもしれないことがあといくつかあります。 グローバル修飾子 /g は一つの文字列に出来るだけ何回もマッチングすることを 許します。 スカラコンテキストでは、文字列に対するマッチングの成功によって /g はマッチングからマッチングにジャンプし、文字列の位置を記録し続けて いきます。 pos() 関数を使って位置を取得または設定できます。 例えば:

    $x = "cat dog house"; # 3 words
    while ($x =~ /(\w+)/g) {
        print "Word is $1, ends at position ", pos $x, "\n";
    }

prints

は以下を表示します

    Word is cat, ends at position 3
    Word is dog, ends at position 7
    Word is house, ends at position 13

A failed match or changing the target string resets the position. If you don't want the position reset after failure to match, add the /c, as in /regex/gc.

マッチングに失敗したり、ターゲット文字列を変更するとこの位置は リセットされます。 もしマッチングに失敗したときに位置をリセットしたくないのであれば、 /regexp/gc のように /c を追加します。

In list context, /g returns a list of matched groupings, or if there are no groupings, a list of matches to the whole regex. So

リストコンテキストでは、/g はマッチングしたグループのリストを返します; グループ化の指定がなければ、正規表現全体にマッチングするリストを返します。 従って

    @words = ($x =~ /(\w+)/g);  # matches,
                                # $word[0] = 'cat'
                                # $word[1] = 'dog'
                                # $word[2] = 'house'
    @words = ($x =~ /(\w+)/g);  # マッチングする
                                # $word[0] = 'cat'
                                # $word[1] = 'dog'
                                # $word[2] = 'house'

検索と置換

Search and replace is performed using s/regex/replacement/modifiers. The replacement is a Perl double-quoted string that replaces in the string whatever is matched with the regex. The operator =~ is also used here to associate a string with s///. If matching against $_, the $_ =~ can be dropped. If there is a match, s/// returns the number of substitutions made; otherwise it returns false. Here are a few examples:

検索と置換は s/regexp/replacement/modifiers を使って処理されます。 replacement は Perlでのダブルクォートで囲まれた文字列で、 regexp にマッチングした文字列を置き換えるものです。 =~ 演算子もまた s/// を伴った文字列に結びつけられるために 使われます。 $_ に対してマッチングを行う場合には、$_ =~ は省略できます。 マッチングに成功した場合には s/// は置換が行われた数を返します; 失敗した場合には偽を返します。 幾つか例を挙げましょう:

    $x = "Time to feed the cat!";
    $x =~ s/cat/hacker/;   # $x contains "Time to feed the hacker!"
    $y = "'quoted words'";
    $y =~ s/^'(.*)'$/$1/;  # strip single quotes,
                           # $y contains "quoted words"
    $x = "Time to feed the cat!";
    $x =~ s/cat/hacker/;   # $x の内容は "Time to feed the hacker!"
    $y = "'quoted words'";
    $y =~ s/^'(.*)'$/$1/;  # シングルクォートを剥ぎ取る
                           # $y の内容は "quoted words"

With the s/// operator, the matched variables $1, $2, etc. are immediately available for use in the replacement expression. With the global modifier, s///g will search and replace all occurrences of the regex in the string:

s/// 演算子を使うにあたって、$1, $2 といったマッチング変数は その置換式のなかで即座に使うことができます。 グローバル修飾子 s///g を使うことで、文字列中のすべての正規表現に マッチングする検索と置換を行います:

    $x = "I batted 4 for 4";
    $x =~ s/4/four/;   # $x contains "I batted four for 4"
    $x = "I batted 4 for 4";
    $x =~ s/4/four/g;  # $x contains "I batted four for four"
    $x = "I batted 4 for 4";
    $x =~ s/4/four/;   # $x の内容は "I batted four for 4"
    $x = "I batted 4 for 4";
    $x =~ s/4/four/g;  # $x の内容は "I batted four for four"

The non-destructive modifier s///r causes the result of the substitution to be returned instead of modifying $_ (or whatever variable the substitute was bound to with =~):

非破壊修飾子 s///r$_ (または =~ によって置換されることになる 変数) を変更する代わりに、置換の結果を返します:

    $x = "I like dogs.";
    $y = $x =~ s/dogs/cats/r;
    print "$x $y\n"; # prints "I like dogs. I like cats."

    $x = "Cats are great.";
    print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~
        s/Frogs/Hedgehogs/r, "\n";
    # prints "Hedgehogs are great."

    @foo = map { s/[a-z]/X/r } qw(a b c 1 2 3);
    # @foo is now qw(X X X 1 2 3)

The evaluation modifier s///e wraps an eval{...} around the replacement string and the evaluated result is substituted for the matched substring. Some examples:

評価修飾子 s///e は置換文字列を eval{...} でラップし、その評価結果を マッチングした部分文字列の置換のために使います。 いくつか例を挙げます:

    # reverse all the words in a string
    $x = "the cat in the hat";
    $x =~ s/(\w+)/reverse $1/ge;   # $x contains "eht tac ni eht tah"
    # 文字列中の全ての単語を逆順にする
    $x = "the cat in the hat";
    $x =~ s/(\w+)/reverse $1/ge;   # $x は "eht tac ni eht tah"
    # convert percentage to decimal
    $x = "A 39% hit rate";
    $x =~ s!(\d+)%!$1/100!e;       # $x contains "A 0.39 hit rate"
    # 百分率を 10 進数に置き換える
    $x = "A 39% hit rate";
    $x =~ s!(\d+)%!$1/100!e;       # $x は "A 0.39 hit rate"

The last example shows that s/// can use other delimiters, such as s!!! and s{}{}, and even s{}//. If single quotes are used s''', then the regex and replacement are treated as single-quoted strings.

最後の例のように、s///s!!!s{}{} 、 果ては s{}// のように異なるデリミタを使うことができます。 s''' のようにシングルクォートが使われた場合、その正規表現と 置換テキストはシングルクォート文字列のように扱われ、変数の置き換えは 行われません。

split 演算子

split /regex/, string splits string into a list of substrings and returns that list. The regex determines the character sequence that string is split with respect to. For example, to split a string into words, use

split /regex/, string, limitstring オペランドを部分文字列の リストに分割し、そのリストを返します。 regex は、string を分割するときに使われる文字並びを決定します。 たとえば、文字列を単語に分割するには以下のようにします

    $x = "Calvin and Hobbes";
    @word = split /\s+/, $x;  # $word[0] = 'Calvin'
                              # $word[1] = 'and'
                              # $word[2] = 'Hobbes'

To extract a comma-delimited list of numbers, use

カンマ区切りの数値リストを展開するには、以下のようにします

    $x = "1.618,2.718,   3.142";
    @const = split /,\s*/, $x;  # $const[0] = '1.618'
                                # $const[1] = '2.718'
                                # $const[2] = '3.142'

If the empty regex // is used, the string is split into individual characters. If the regex has groupings, then the list produced contains the matched substrings from the groupings as well:

// が使われた場合には、文字列は個々の文字に分割されます。 正規表現がグループ化を伴っていた場合には、グループ化されたものも部分文字列に 含まれるようになります:

    $x = "/usr/bin";
    @parts = split m!(/)!, $x;  # $parts[0] = ''
                                # $parts[1] = '/'
                                # $parts[2] = 'usr'
                                # $parts[3] = '/'
                                # $parts[4] = 'bin'

Since the first character of $x matched the regex, split prepended an empty initial element to the list.

$x の最初の文字に正規表現がマッチングしているので、split はリストの 最初の要素に空要素を置きます。

use re 'strict'

New in v5.22, this applies stricter rules than otherwise when compiling regular expression patterns. It can find things that, while legal, may not be what you intended.

これは v5.22 からの新機能で、正規表現パターンをコンパイルするときに他よりも より厳密な規則を適用します。 これにより、有効ではあるけれども、意図しているものと違うかも知れないものを 見つけることができます。

'strict' in re を参照してください。

バグ

None.

なし。

SEE ALSO

This is just a quick start guide. For a more in-depth tutorial on regexes, see perlretut and for the reference page, see perlre.

これは単なるクイックスタートガイドです。 正規表現に関するより深いチュートリアルについては perlretut を、 リファレンスについては perlre を参照してください。

AUTHOR AND COPYRIGHT

Copyright (c) 2000 Mark Kvale All rights reserved.

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

Acknowledgments

The author would like to thank Mark-Jason Dominus, Tom Christiansen, Ilya Zakharevich, Brad Hughes, and Mike Giroux for all their helpful comments.