Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

正規表現で使える組込み変数

今日は冬至です。
Wikipedia英語版によると

> winter_solstice = "Winter solstice is an astronomical phenomenon which for the Northern Hemisphere occurs in December and which for the Southern Hemisphere occurs in June."
#=> "Winter solstice is an astronomical phenomenon which for the Northern Hemisphere occurs in December and which for the Southern Hemisphere occurs in June."

てな解説が出ています。
この文から北半球という文字列を抽出する場合

> /the Northern Hemisphere/ =~ winter_solstice
#=> 56

といった正規表現で行けます。

さて、本題はここからです。
正規表現の結果はRubyの組込み定数にて扱う事ができます。
$1なんかは良く使っていたのですが、他にも知らない物が結構あったので備忘録ついでにメモしておきます。

組み込み変数

$~ 最後にマッチしたときの情報(MatchData オブジェクト)

> p $~
#<MatchData "the Northern Hemisphere">
=> #<MatchData "the Northern Hemisphere">

$& マッチしたテキスト全体

> p $&
"the Northern Hemisphere"
#=> "the Northern Hemisphere"

$` マッチしたテキストの手前の文字列

> p $`
"Winter solstice is an astronomical phenomenon which for "
#=> "Winter solstice is an astronomical phenomenon which for "

$' マッチしたテキストの後ろの文字列

> p $'
" occurs in December and which for the Southern Hemisphere occurs in June."
#=> " occurs in December and which for the Southern Hemisphere occurs in June."

$1, $2, ... キャプチャ文字列

> /(the )(Northern )(Hemisphere )/ =~ winter_solstice
#=> 56

> p $1
"the "
#=> "the "

> p $2
"Northern "
#=> "Northern "

> p $3
"Hemisphere "
=> "Hemisphere "

> p $4
nil
#=> nil

$+ 最後(末尾)のキャプチャ文字列

> /(the )(Northern )(Hemisphere )/ =~ winter_solstice
#=> 56

> p $+
"Hemisphere "
#=> "Hemisphere "

参考もと