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
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"]
m = /(.)(.)(\d+)(\d)/.match("THX1138.")
m.begin(0) → 1
m.begin(2) → 2
m = /(.)(.)(\d+)(\d)/.match("THX1138.")
m.end(0) → 7
m.end(2) → 3
m = /(.)(.)(\d+)(\d)/.match("THX1138.")
m.length → 5
m.size → 5
m = /(.)(.)(\d+)(\d)/.match("THX1138.")
m.offset(0) → [1, 7]
m.offset(4) → [6, 7]
m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
m.post_match → ": The Movie"
m = /(.)(.)(\d+)(\d)/.match("THX1138.")
m.pre_match → "T"
MatchData#length
.
match
.
m = /(.)(.)(\d+)(\d)/.match("THX1138.")
m.string → "THX1138."
m = /(.)(.)(\d+)(\d)/.match("THX1138.")
m.to_a → ["HX1138", "H", "X", "113", "8"]
m = /(.)(.)(\d+)(\d)/.match("THX1138.")
m.to_s → "HX1138"
Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).
Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.