Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Regexp | last_match

概要

Regexp#last_match -> MatchData
Regexp#last_match(nth) -> String | nil

詳細

カレントスコープで最後に行った正規表現マッチの MatchData オ ブジェクトを返却。
$~ と同じ。

RuboCop では $~ よりも、こちらが推奨される。
引数 nth 付きの場合は、 nth 番目にマッチした値を返却。
$& と同じ。

サンプルコード
require 'tbpgr_utils'

"hogehigehagebar" =~ /(h.ge)(h.ge)(h.ge)/

bulk_puts_eval binding, <<-EOS
$~
Regexp.last_match
$~ == Regexp.last_match
Regexp.last_match(0)
$&
Regexp.last_match(1)
Regexp.last_match(2)
Regexp.last_match(3)
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

$~                      # => #<MatchData "hogehigehage" 1:"hoge" 2:"hige" 3:"hage">
Regexp.last_match       # => #<MatchData "hogehigehage" 1:"hoge" 2:"hige" 3:"hage">
$~ == Regexp.last_match # => true
Regexp.last_match(0)    # => "hogehigehage"
$&                      # => "hogehigehage"
Regexp.last_match(1)    # => "hoge"
Regexp.last_match(2)    # => "hige"
Regexp.last_match(3)    # => "hage"