Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method · added in Ruby 3.1

MatchData#match

mtch.match(n) → string or nil

Returns the captured substring corresponding to the argument. n can be a string or symbol to reference a named capture.

Example
m = /(.)(.)(\d+)(\d)(\w)?/.match("THX1138.")
m.match(0)       #=> "HX1138"
m.match(4)       #=> "8"
m.match(5)       #=> nil

m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
m.match(:foo)    #=> "h"
m.match(:bar)    #=> "ge"

Ruby version changes

  1. 3.1
See also #length #match_length #inspect #named_captures also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2