Ruby 4.0 リファレンスマニュアル

singleton method Regexp.last_match

last_match -> MatchData | nil[permalink][rdoc][edit]
() → MatchData?

カレントスコープで最後に行った正規表現マッチの MatchData オブジェクトを返します。このメソッドの呼び出しは $~ の参照と同じです。

/(.)(.)/ =~ "ab"
p Regexp.last_match      # => #<MatchData "ab" 1:"a" 2:"b">
p Regexp.last_match[0]   # => "ab"
p Regexp.last_match[1]   # => "a"
p Regexp.last_match[2]   # => "b"
p Regexp.last_match[3]   # => nil
last_match(nth) -> String | nil[permalink][rdoc][edit]
(MatchData::capture capture) → String?

整数 nth0 の場合、マッチした文字列を返します($&)。それ以外では、nth 番目の括弧にマッチした部分文字列を返します($1, $2, ...)。対応する括弧がない場合やマッチしなかった場合には nil を返します。

/(.)(.)/ =~ "ab"
p Regexp.last_match(0)   # => "ab"
p Regexp.last_match(1)   # => "a"
p Regexp.last_match(2)   # => "b"
p Regexp.last_match(3)   # => nil

正規表現全体がマッチしなかった場合、引数なしの Regexp.last_matchnil を返すため、 last_match[1] の形式では例外 NoMethodError が発生します。対して、last_match(1)nil を返します。

str = "This is Regexp"
/That is Regexp/ =~ str
p Regexp.last_match # => nil
begin
  Regexp.last_match[1] # ~> NoMethodError
rescue
  puts $! # => undefined method '[]' for nil:NilClass
end
p Regexp.last_match(1) # => nil
[PARAM] nth:
整数を指定します。整数 nth0 の場合、マッチした文字列を返します。それ以外では、nth 番目の括弧にマッチした部分文字列を返します。