正規表現(2) 検索パターン
Perl で正規表現検索パターンを記述するには、前後を「m/」と「/」で囲みます。「m」は省略できます。
m/Windows (3\.1|95|98|NT|Me|2000|XP|2003|Vista)/ # m// 各種Windowsを検索
/Windows (3\.1|95|98|NT|Me|2000|XP|2003|Vista)/ # 上と同じ意味
文字列に正規表現を適用するには、以下のように「=~」という演算子を使います。文字列に「m//」(正規表現検索パターン)を適用すると、文字列の中からパターンを検索する事ができます。
文字列に検索パターンがマッチした場合(文字列が検索パターンを含んでいた場合)真が返され、マッチしなかった場合は偽が返されます。
use strict;
my $text = "The first OS I used was Windows 95.";
if ($text =~ m/Windows (3\.1|95|98|NT|Me|2000|XP|2003|Vista)/) {
print "Windows OS is in the text.\n";
} else {
print "Windows OS is not in the text.\n";
}
「=~」演算子を使わずに正規表現パターンだけ書いた場合は、「$_」が対象になります。以下のコードは上のものと同じ意味です。
use strict;
$_ = "The first OS I used was Windows 95.";
if (/Windows (3\.1|95|98|NT|Me|2000|XP|2003|Vista)/) {
print "Windows OS is in the text.\n";
} else {
print "Windows OS is not in the text.\n";
}
実行結果です。
Windows OS is in the text.
ちゃんと検索できています。
試しに $text を変えてみると……
use strict;
my $text = "The first OS I used was Linux";
if ($text =~ m/Windows (3\.1|95|98|NT|Me|2000|XP|2003|Vista)/) {
print "Windows OS is in the text.\n";
} else {
print "Windows OS is not in the text.\n";
}
Windows OS is not in the text.
と、ちゃんと「ありません」と表示されます。(^_^)
ちなみに、「m」を付けている場合は正規表現を囲う「/」(スラッシュ)を、他の文字に変えられます。開きカッコ({[(< など)を開始の文字に使うと、対応した閉じカッコが終わりの文字になります。(q や qq などと同じです)
m|Perl Monger|
m{Palmo}
m(Regular Expression)
今日はここまで。明日からどしどし正規表現を使ってみます。
正規表現は使いこなせばとても便利なので、もし知らなかったら、ぜひぜひ勉強してみてくださいね。(^_^)