正規表現のデバッグ方法
re=debugってやると詳細出してくれるの知らなかったのでコピペ。
502+1 :nobodyさん [] :2011/05/02(月) 02:42:13.10 ID: fV7VGj7j (1/2)
「文字列A 文字列B」
という 2 つの文字列の間に複数の空白がある行において
/\s*/ でマッチさせると、変数 $` (=$PREMATCH) には何も入りませんでした
なぜでしょうか?入門書は「パターンマッチが複数解釈出来る場合には一番長い解釈にマッチする」とあります。
よって自分は \s* という「0 回以上のホワイトスペースの繰り返し」は
最も長い解釈では複数の空白にマッチし
$` には文字列A が代入されるはずだと考えたのですが
503+1 :1/2 [↓] :2011/05/02(月) 03:50:24.42 ID:???
>>502
その本の説明が曖昧なのか読み違えているのだろう。http://perldoc.jp/docs/perl/5.10.1/perlre.pod#Quantifiers
> (始めた地点から)可能な限り多くを先にあるパターンでマッチングさせます。/\s*/ は0文字以上の空白文字なので、先頭の0文字 = 文字列Aの前でマッチし、
そこで全てのマッチングが成功して終わる。更に長くマッチできる他の場所を
探すような事はしてくれない。
504+1 :2/2 [↓] :2011/05/02(月) 03:51:10.81 ID:???
> perl -Mre=debug -e "qq/abc def/ =~ /\s*/" Compiling REx "\s*" Final program: 1: STAR (3) 2: SPACE (0) 3: END (0) minlen 0 Matching REx "\s*" against "abc def" 0 <> <abc def> | 1:STAR(3) SPACE can match 0 times out of 2147483647... 0 <> <abc def> | 3: END(0) Match successful! Freeing REx: "\s*" > perl -Mre=debug -e "qq/abc def/ =~ /\s+/" Compiling REx "\s+" Final program: 1: PLUS (3) 2: SPACE (0) 3: END (0) stclass SPACE plus minlen 1 Matching REx "\s+" against "abc def" Matching stclass SPACE against "abc def" (7 chars) 3 <abc> < def> | 1:PLUS(3) SPACE can match 1 times out of 2147483647... 4 <abc > <def> | 3: END(0) Match successful! Freeing REx: "\s+"