正規表現についていくつか
$1とか$2とかについて
選択させたい部分をカッコで囲むことがあるけど、やっぱりそれも$1とか$2とかを束縛するのかな?やってみよう。
my $str = 'interior and exterior'; while ($str =~ /(in|ex)\w+/g) { print "\$& = $&, \$1 = $1\n"; }
http://ideone.com/t8SPu
ちゃんと$1で取り出せた。
正規表現内のスペース
my $str = 'foo bar baz qux'; if ($str =~ /z q/) { print "$&\n"; }
http://ideone.com/NvFbg
無視されたりメタ文字になったりしない。スペースという文字そのものにマッチする。
修飾子/gに関して
whileとともに用いるとマッチした部分を列挙できるけど、whileの条件式に与えている式は変化しないのにイテレータのような動きをしている点が不思議に思えるなぁ。
正規表現の中のカッコって何だっけ?
以下の2つのスクリプトの実行結果が違う。なんぞ?
my $str = 'The price is 300yen. The distance is 120km.'; my @match = ($str =~ /\d+[a-zA-Z]+/g); print join(',', @match), "\n";
my $str = 'The price is 300yen. The distance is 120km.'; my @match = ($str =~ /(\d+)([a-zA-Z]+)/g); print join(',', @match), "\n";
あれ?カッコってどんな意味があるんだっけ?
http://ideone.com/5e1rM http://ideone.com/Z49PN
なんで http://ideone.com/A81Xv では
300 yen 120 km
にならなかったんだろ?