MatchData is the type of the special variable $~, and is the type of the object returned by Regexp#match and Regexp#last_match. It encapsulates all the results of a pattern match, results normally accessed through the special variables $&, $’, $`, $1, $2, and so on. Matchdata is also known as MatchingData.
Match Reference—MatchData acts as an array, and may be accessed using the normal array indexing techniques. mtch[0] is equivalent to the special variable $&, and returns the entire matched string. mtch[1], mtch[2], and so on return the values of the matched backreferences (portions of the pattern between parentheses).
m = /(.)(.)(\d+)(\d)/.match("THX1138.") m[0] #=> "HX1138" m[1, 2] #=> ["H", "X"] m[1..3] #=> ["H", "X", "113"] m[-3, 2] #=> ["X", "113"]
Returns the number of elements in the match array.
m = /(.)(.)(\d+)(\d)/.match("THX1138.") m.length #=> 5 m.size #=> 5
Returns a two-element array containing the beginning and ending offsets of the nth match.
m = /(.)(.)(\d+)(\d)/.match("THX1138.") m.offset(0) #=> [1, 7] m.offset(4) #=> [6, 7]
Returns the portion of the original string after the current match. Equivalent to the special variable $’.
m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie") m.post_match #=> ": The Movie"
Returns the portion of the original string before the current match. Equivalent to the special variable $`.
m = /(.)(.)(\d+)(\d)/.match("THX1138.") m.pre_match #=> "T"
Uses each index to access the matching values, returning an array of the corresponding matches.
m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie") m.to_a #=> ["HX1138", "H", "X", "113", "8"] m.select(0, 2, -2) #=> ["HX1138", "X", "113"]
Returns the number of elements in the match array.
m = /(.)(.)(\d+)(\d)/.match("THX1138.") m.length #=> 5 m.size #=> 5
Returns a frozen copy of the string passed in to match.
m = /(.)(.)(\d+)(\d)/.match("THX1138.") m.string #=> "THX1138."
Returns the array of matches.
m = /(.)(.)(\d+)(\d)/.match("THX1138.") m.to_a #=> ["HX1138", "H", "X", "113", "8"]
Because to_a is called when expanding *variable, there‘s a useful assignment shortcut for extracting matched fields. This is slightly slower than accessing the fields directly (as an intermediate array is generated).
all,f1,f2,f3 = *(/(.)(.)(\d+)(\d)/.match("THX1138.")) all #=> "HX1138" f1 #=> "H" f2 #=> "X" f3 #=> "113"
Returns the entire matched string.
m = /(.)(.)(\d+)(\d)/.match("THX1138.") m.to_s #=> "HX1138"
ruby-doc.org is a service of James Britt and Neurogami, a Ruby application development company in Phoenix, AZ.
Documentation content on ruby-doc.org is provided by remarkable members of the Ruby community.
For more information on the Ruby programming language, visit ruby-lang.org.
Want to help improve Ruby's API docs? See Ruby Documentation Guidelines.