正規表現といっても、+が1つ以上の繰り返しとかそんなことを書くわけではないのでスイマセン。
Rubyで正規表現を扱う時によく書くパターン(と思われる)コードは下のような感じになる。
pattern = /([a-z]+)/
str = gets.chomp
if str =~ pattern
puts $1
else
puts "not match"
end
標準入力から読み込んだ文字列から、小文字のアルファベットが続く部分を抜き出す。
この時に使ってる$1とかが今回の説明する部分になる。
これってPerlライクな書き方になってるけど、そういう書き方は嫌じゃ!!って言う人はちゃんと別の書き方が用意されてる。
pattern = Regexp.compile("([a-z]+)")
str = gets.chomp
if match = pattern.match(str)
puts match[0]
else
puts "not match"
end
Regexpのcompileで正規表現オブジェクトを作って、それのmatchメソッドで正規表現にマッチした部分の情報を持つMatchDataクラスのオブジェクトが取得できる。(マッチする部分が無かったらnil)
これの[]演算子を使って$1とかに相当するものが取得できる。
$1,$2,$3って何だ?って思いながら使ってたけど、これって$~[0],$~[1],$~[2]と同じ意味らしい。
$~って何だ?ってのは、正規表現のmatchを呼び出したときにMatchDataをこっそり入れてるみたい。
自分のコードから$~ = matchみたいに設定すると$1 $2とかで取得できるものを任意のMatchDataに置きかえれる。
普通はしないだろうけど…