class MatchData
A match of a Regexp in a string: the matched text, its groups and
where they are. Positions are character indices. Made by
String#match, String#matches, Regexp#match and given to the
blocks of String#sub, String#gsub and String#scan.
m = "on 2024-10 now".matches(/(?<y>\d+)-(?<m>\d+)/)[0]
m[0] # => "2024-10"
m["y"] # => "2024"
m.pre_match # => "on "
m.begin(0) # => 3
<prelude>:2874
Methods
def [](index: Int) -> String?
The text of group index (0 is the whole match), or nil when the
group took no part or there is no such group. Unlike Ruby's, a
negative index gives nil.
<prelude>:2880
def [](name: String) -> String?
The text of the group named name, or nil when it took no part.
Raises
IndexError when the pattern has no group of that name.
<prelude>:2886
def pre_match -> String
The text before the match.
<prelude>:2888
def post_match -> String
The text after the match.
<prelude>:2890
def captures -> Array[String?]
The texts of the groups (not the whole match), nil for one that
took no part.
"aé".match(/(é)(x)?/)&.captures # => ["é", nil]
<prelude>:2897
def named_captures -> Hash[String, String?]
The named groups' texts by name, nil for one that took no part.
<prelude>:2899
def names -> Array[String]
The names of the named groups, in order.
<prelude>:2901
def values_at(*indices: Int) -> Array[String?]
The texts of the groups at indices, as #[] gives them.
<prelude>:2903
def to_a -> Array[String?]
The whole match followed by the groups' texts.
<prelude>:2905
def size -> Int
The number of groups plus one (for the whole match).
<prelude>:2907
def to_s -> String
The matched text.
<prelude>:2909
def inspect -> String
The match and its groups, as #<MatchData "2024-10" y:"2024" m:"10">.
<prelude>:2911
def begin(index: Int) -> Int?
The character index where group index starts (0: the whole match),
or nil when the group took no part.
Raises
IndexError when there is no group index.
m = "aéb".match(/(é)(x)?/)
m&.begin(1) # => 1
m&.end(1) # => 2
m&.begin(2) # => nil
<prelude>:2925
def end(index: Int) -> Int?
The character index just after the end of group index (0: the
whole match), or nil when the group took no part.
Raises
IndexError when there is no group index.
<prelude>:2932