Class: MatchData
Overview
::Ruby matcher methods create MatchData objects.
A MatchData object contains the detailed result of a match, including:
- The target string used for the match.
- The Regexp used for the match.
- The matched substring.
- The substring preceding the matched substring.
- The substring following the matched substring.
- Captured substrings.
In Brief
### Basics.
s = 'https://docs.ruby-lang.org/en/2.5.0/MatchData.html'
m = s.match(/(\d\.?)+/) # => #<MatchData "2.5.0" 1:"0">
m.string # => "https://docs.ruby-lang.org/en/2.5.0/MatchData.html"
m.regexp # => /(\d\.?)+/
m[0] # => "2.5.0" # Matched substring.
m.pre_match # => "https://docs.ruby-lang.org/en/"
m.post_match # => "/MatchData.html"
### Unnamed (numbered) captures.
m = "2025-12-25".match(/(\d{4})-(\d{2})-(\d{2})/)
### => #<MatchData "2025-12-25" 1:"2025" 2:"12" 3:"25">
m[0] # => "2025-12-25" # Entire matched substring.
m[1] # => "2025" # First captured substring.
m[2] # => "12" # Second captured substring.
m[3] # => "25" # Third captured substring.
m[4] # => nil # No more captured substrings.
### Named captures.
m = "2025-12-25".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)
m[:year] # "2025"
m[:month] # "12"
m[:day] # "25"
### Also available by numbers.
m[0] # => "2025-12-25"
m[1] # => "2025"
m[:nosuch] # Raises IndexError: undefined group name reference: nosuch.
Matcher Methods
Each of these methods creates a MatchData object, updates the matcher global variables, and returns the MatchData object:
Each of these methods creates a MatchData object, updates the matcher global variables, but does not return the MatchData object; the MatchData object is available in global variable $~:
Each of these methods, when called with a Regexp argument, creates a MatchData object, updates the matcher global variables, but does not return the MatchData object; the MatchData object is available in global variable $~:
- String#index
- String#partition
- String#rindex
- String#rpartition
- String#slice
- String#slice!
- String#split
Match-Related Methods
Each of these predicate methods performs a "fast match," returning whether a match was found, but not creating a MatchData object, and not setting matcher global variables:
This method return the MatchData object resulting from the most recent match:
What's Here
First, what's elsewhere. Class MatchData:
- Inherits from class Object.
Here, class MatchData provides methods that are useful for:
General Methods
- #== (aliased as #eql?): returns whether
selfand another object are equal. - #hash: returns the integer hash value for
self. - #inspect: returns a string representation of
self. - #post_match: returns the substring that follows the matched string.
- #pre_match: returns the substring that precedes the matched string.
- #regexp: returns the Regexp used to produce
self. - #size (aliased as #length): returns the size of the array of matched substrings.
- #string: returns the string used to produce
self. - #to_a: returns the array of matched substrings.
- #to_s: returns a string representation of
self.
Capture Methods
Each of these methods returns information about all captures:
- #captures (aliased as #deconstruct): returns an array of the captured substrings.
- #named_captures: returns a hash of the named captures.
- #names: returns an array of the capture names.
Each of these methods returns information about one capture, which may be specified by its integer index or by its name (if it is a named capture):
- #[]: returns a matched substring or an array of matched substrings for the given arguments.
- #begin: returns the character offset of the beginning of the capture.
- #bytebegin: returns the byte offset of the beginning of the capture.
- #byteend: returns the byte offset of the end of the capture.
- #byteoffset: returns the byte offsets of the beginning and end of the capture.
- #deconstruct_keys: returns a hash of the names and values for the given names.
- #end: returns the character offset of the end of the capture.
- #integer_at: returns the value of the capture, converted to an integer.
- #match: returns the matched substring for the capture.
- #match_length: returns the length (in characters) of the matched substring for the capture.
- #offset: returns the begin and end offsets for the capture.
- #values_at: returns a matched substring or an array of matched substrings for the given arguments.
Instance Method Summary
- #==(object) ⇒ Boolean (also: #eql?)
-
#[](n) ⇒ String?
With only integer argument
ngiven, returns the matched substring at offsetn: -
#begin(n) ⇒ Integer
Returns the offset (in characters) of the beginning of the specified match.
-
#bytebegin(n) ⇒ Integer
Returns the offset (in bytes) of the beginning of the specified match.
-
#byteend(n) ⇒ Integer
Returns the offset (in bytes) of the end of the specified match.
-
#byteoffset(object) ⇒ Array, byteend
Returns the offsets (in bytes) of the beginning and end of the specified match.
-
#captures ⇒ Array
(also: #deconstruct)
Returns an array of the captured substrings, including all except the entire matched substring:
-
#deconstruct ⇒ Array
Alias for #captures.
-
#deconstruct_keys(object) ⇒ Hash
With an array of symbol capture names given, returns a hash of the names and values for the given names:
-
#end(n) ⇒ Integer
Returns the offset (in characters) of the end of the specified match.
-
#eql?(object) ⇒ Boolean
Alias for #==.
-
#hash ⇒ Integer
Returns the integer hash value for
self, based on its target string, regexp, match, and captures. -
#inspect ⇒ String
Returns a string representation of
self: -
#integer_at(n, radix = 10) ⇒ Integer?
Returns a captured substring converted to an integer; the substring is interpreted as a numeric string in the given
radix. -
#length ⇒ Integer
(also: #size)
Returns size of the match array:
-
#match(n) ⇒ String?
Returns the matched substring corresponding to the given argument.
-
#match_length(n) ⇒ Integer
Returns the length (in characters) of the matched substring corresponding to the given argument.
-
#named_captures(symbolize_names: false) ⇒ Hash
Returns a hash of capture names and values:
-
#names ⇒ array_of_strings
Returns an array containing the capture names:
-
#offset(n) ⇒ Array, end_offset
Returns the offsets (in characters) of the beginning (#begin value) and end (#end value) of the specified match.
-
#post_match ⇒ String
Returns the substring of the target string that follows the matched substring; equivalent to Regexp global variable $':
-
#pre_match ⇒ String
Returns the substring of the target string that precedes the matched substring; equivalent to Regexp global variable $`</tt>:
-
#regexp ⇒ Regexp
Returns the
::Regexpthat produced the match: -
#size ⇒ Integer
Alias for #length.
-
#string ⇒ String
Returns the target string if it was frozen; otherwise, returns a frozen copy of the target string:
-
#to_a ⇒ Array
Returns the array of matched substrings:
-
#to_s ⇒ String
Returns the matched substring; equivalent to #match(0):
-
#values_at(*indexes) ⇒ Array
Returns an array of matched substrings as specified by the given
indexes, which may be any mixture of integers, names, and ranges. - #initialize_copy(orig) Internal use only
Instance Method Details
#==(object) ⇒ Boolean Also known as: #eql?
Returns whether object is a MatchData object
whose #string, #regexp, and #begin values are the same as those of self:
regexp = /a/
s = 'aba'
match0 = regexp.match(s)
match1 = regexp.match(s, 2)
match0[0] # => "a"
match1[0] # => "a"
match0.begin(0) # => 0
match1.begin(0) # => 2
match0 == match0 # => true
match0 == match1 # => false
# File 're.c', line 4384
static VALUE
match_equal(VALUE match1, VALUE match2)
{
if (match1 == match2) return Qtrue;
if (!RB_TYPE_P(match2, T_MATCH)) return Qfalse;
if (!RMATCH(match1)->regexp || !RMATCH(match2)->regexp) return Qfalse;
if (!rb_str_equal(RMATCH(match1)->str, RMATCH(match2)->str)) return Qfalse;
if (!rb_reg_equal(match_regexp(match1), match_regexp(match2))) return Qfalse;
int num_regs = RMATCH_NREGS(match1);
if (num_regs != RMATCH_NREGS(match2)) return Qfalse;
if (memcmp(RMATCH_BEG_PTR(match1), RMATCH_BEG_PTR(match2), num_regs * sizeof(OnigPosition))) return Qfalse;
if (memcmp(RMATCH_END_PTR(match1), RMATCH_END_PTR(match2), num_regs * sizeof(OnigPosition))) return Qfalse;
return Qtrue;
}
With only integer argument n given,
returns the matched substring at offset n:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match[0] # => "2026-12-25" # Entire matched string.
match[1] # => "2026" # First matched substring.
match[2] # => "12" # Second matched substring.
match[3] # => "25" # Third matched substring.
match[4] # => nil # No more matches.
match[-1] # => "25" # For negative offset, counts backwards.
With integer arguments n and #size given,
returns #size matched substrings beginning at offset n:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match[0, 1] # => ["2026-12-25"]
match[0, 4] # => ["2026-12-25", "2026", "12", "25"]
match[0, 10] # => ["2026-12-25", "2026", "12", "25"]
match[-3, 2] # => ["2026", "12"]
match[0, 0] # => []
With string or symbol argument name given,
returns the named matched substring:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = regexp.match('2026-10-27')
#### => #<MatchData "2026-10-27" year:"2026" month:"10" day:"27">
match[:year] # => "2026"
match['day'] # => "27"
match[:nosuch] # Raises IndexError : undefined group name reference: nosuch.
If multiple captures have the same name, returns matched substring for the last one.
With bounded range argument range given,
returns an array of matched substrings:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => {#<}MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match[0..2] # => ["2026-12-25", "2026", "12"]
match[0..10] # => ["2026-12-25", "2026", "12", "25"]
match[0..-3] # => ["2026-12-25", "2026"]
match[-3..2] # => ["2026", "12"]
With beginless range argument range given,
returns an array of matched substrings:
match[..0] # => ["2026-12-25"]
match[..1] # => ["2026-12-25", "2026"]
match[..10] # => ["2026-12-25", "2026", "12", "25"]
With endless range argument range given,
returns an array of matched substrings:
match[0..] # => ["2026-12-25", "2026", "12", "25"]
match[2..] # => ["12", "25"]
match[10..] # => nil
With unbounded range argument range given,
returns an array of all matched substrings:
match[nil..nil] # => ["2026-12-25", "2026", "12", "25"]
# File 're.c', line 2911
static VALUE
match_aref(int argc, VALUE *argv, VALUE match)
{
VALUE idx, length;
match_check(match);
rb_scan_args(argc, argv, "11", &idx, &length);
if (NIL_P(length)) {
if (FIXNUM_P(idx)) {
return rb_reg_nth_match(FIX2INT(idx), match);
}
else {
int num = namev_to_backref_number(match, idx);
if (num >= 0) {
return rb_reg_nth_match(num, match);
}
else {
return match_ary_aref(match, idx, Qnil);
}
}
}
else {
rb_len_t beg = NUM2LEN(idx);
rb_len_t len = NUM2LEN(length);
rb_len_t num_regs = RMATCH_NREGS(match);
if (len < 0) {
return Qnil;
}
if (beg < 0) {
beg += num_regs;
if (beg < 0) return Qnil;
}
else if (beg > num_regs) {
return Qnil;
}
if (beg+len > num_regs) {
len = num_regs - beg;
}
return match_ary_subseq(match, beg, len, Qnil);
}
}
Returns the offset (in characters) of the beginning of the specified match.
With non-negative integer argument n given,
returns the character offset of the beginning of the nth match:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match[0] # => "2026-12-25"
match.begin(0) # => 0
match[3] # => "25"
match.begin(3) # => 8
match.begin(10) # Raises IndexError: index 10 out of matches.
match = /(ん)(に)(ち)/.match('こんにちは')
#### => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
match[2] # => "に"
match.begin(2) # => 2 # Character offset.
match.bytebegin(2) # => 6 # Byte offset.
With string or symbol argument name given,
returns the offset of the beginning for the named match:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match[:year] # => "2026"
match.begin(:year) # => 0
match.begin('month') # => 5
Related: #bytebegin.
# File 're.c', line 1797
static VALUE
match_begin(VALUE match, VALUE n)
{
int i = match_backref_number(match, n);
match_check(match);
backref_number_check(match, i);
if (RMATCH_BEG(match, i) < 0)
return Qnil;
update_char_offset(match);
return LEN2NUM(RMATCH(match)->char_offset[i].beg);
}
Returns the offset (in bytes) of the beginning of the specified match.
With non-negative integer argument n given,
returns the offset of the beginning of the nth match:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match[0] # => "2026-12-25"
match.bytebegin(0) # => 0
match[2] # => "12"
match.bytebegin(2) # => 5
match.bytebegin(20) # Raises IndexError: index 20 out of matches.
match = /(ん)(に)(ち)/.match('こんにちは')
#### => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
match[2] # => "に"
match.bytebegin(2) # => 6 # Byte offset.
match.begin(2) # => 2 # Character offset.
With string or symbol argument name given,
returns the offset of the beginning for the named match:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match[:month] # => "12"
match.bytebegin(:month) # => 5
match.bytebegin('day') # => 8
Related: #begin.
# File 're.c', line 1678
static VALUE
match_bytebegin(VALUE match, VALUE n)
{
int i = match_backref_number(match, n);
match_check(match);
backref_number_check(match, i);
if (RMATCH_BEG(match, i) < 0)
return Qnil;
return LEN2NUM(RMATCH_BEG(match, i));
}
Returns the offset (in bytes) of the end of the specified match.
When non-negative integer argument n is given,
returns the offset of the end of the nth match:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match[1] # => "2026"
match.byteend(1) # => 4
match[3] # => "25"
match.byteend(3) # => 10
match.byteend(4) # Raises IndexError: index 4 out of matches.
match = /(ん)(に)(ち)/.match('こんにちは')
#### => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
match[1] # => "ん"
match.byteend(1) # => 6 # Byte offset.
match.end(1) # => 2 # Character offset.
When string or symbol argument name is given,
returns the offset of the end for the named match:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match[:year] # => "2026"
match.byteend(:year) # => 4
match['day'] # => "25"
match.byteend('day') # => 10
Related: #bytebegin.
# File 're.c', line 1738
static VALUE
match_byteend(VALUE match, VALUE n)
{
int i = match_backref_number(match, n);
match_check(match);
backref_number_check(match, i);
if (RMATCH_BEG(match, i) < 0)
return Qnil;
return LEN2NUM(RMATCH_END(match, i));
}
#byteoffset(object) ⇒ Array, byteend
Returns the offsets (in bytes) of the beginning and end of the specified match.
With argument object given as a non-negative integer argument n given,
returns the offsets of the nth match:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match[1] # => "2026"
match.byteoffset(1) # => [0, 4]
match[3] # => "25"
match.byteoffset(3) # => [8, 10]
match.byteoffset(10) # Raises IndexError: index 10 out of matches.
match = /(ん)(に)(ち)/.match('こんにちは')
#### => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
match[1] # => "ん"
match.byteoffset(1) # => [3, 6] # Byte offsets.
match.offset(1) # => [1, 2] # Character offsets.
With argument object given as a string or symbol argument name,
returns the offsets of the named match:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match[:year] # => "2026"
match.byteoffset(:year) # => [0, 4]
match.byteoffset('day') # => [8, 10]
Related: #offset.
# File 're.c', line 1619
static VALUE
match_byteoffset(VALUE match, VALUE n)
{
int i = match_backref_number(match, n);
match_check(match);
backref_number_check(match, i);
if (RMATCH_BEG(match, i) < 0)
return rb_assoc_new(Qnil, Qnil);
return rb_assoc_new(LEN2NUM(RMATCH_BEG(match, i)), LEN2NUM(RMATCH_END(match, i)));
}
#captures ⇒ Array Also known as: #deconstruct
Returns an array of the captured substrings, including all except the entire matched substring:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match.captures # => ["2026", "12", "25"]
match[1..] # => ["2026", "12", "25"] # Included in array.
match[0] # => "2026-12-25" # Not included in array.
Related: #to_a.
# File 're.c', line 2714
static VALUE
match_captures(VALUE match)
{
return match_array(match, 1);
}
Alias for #captures.
#deconstruct_keys(object) ⇒ Hash
With an array of symbol capture names given, returns a hash of the names and values for the given names:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match.deconstruct_keys([:day, :month]) # => {day: "25", month: "12"}
match.deconstruct_keys(['foo']) # Raises TypeError: wrong argument type String (expected Symbol).
Ignores symbols that are not capture names:
match.deconstruct_keys([:foo]) # => {}
With nil given,
returns a hash of all capture names and values:
match.deconstruct_keys(nil) # => {year: "2026", month: "12", day: "25"}
Returns an empty hash if no named captures were defined:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match.deconstruct_keys(nil) # => {}
# File 're.c', line 3234
static VALUE
match_deconstruct_keys(VALUE match, VALUE keys)
{
VALUE h;
rb_len_t i;
match_check(match);
if (NIL_P(RMATCH(match)->regexp)) {
return rb_hash_new();
}
if (NIL_P(keys)) {
h = rb_hash_new_capa(onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)));
struct named_captures_data data = { h, match, 1 };
onig_foreach_name(RREGEXP_PTR(RMATCH(match)->regexp), match_named_captures_iter, &data);
return h;
}
Check_Type(keys, T_ARRAY);
if (onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)) < RARRAY_LEN(keys)) {
return rb_hash_new();
}
h = rb_hash_new_capa(RARRAY_LEN(keys));
for (i=0; i<RARRAY_LEN(keys); i++) {
VALUE key = RARRAY_AREF(keys, i);
VALUE name;
Check_Type(key, T_SYMBOL);
name = rb_sym2str(key);
int num = match_name_to_backref_number(match, name);
if (num >= 0) {
rb_hash_aset(h, key, rb_reg_nth_match(num, match));
}
else {
return h;
}
}
return h;
}
Returns the offset (in characters) of the end of the specified match.
With non-negative integer argument n given,
returns the character offset of the end of the nth match:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match[0] # => "2026-12-25"
match.end(0) # => 10
match[3] # => "25"
match.end(3) # => 10
match.end(10) # Raises IndexError: index 10 out of matches.
match = /(ん)(に)(ち)/.match('こんにちは')
#### => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
match[2] # => "に"
match.end(2) # => 3 # Character offset.
match.byteend(2) # => 9 # Byte offset.
With string or symbol argument name given, returns the offset of the end for the named match:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match[:year] # => "2026"
match.end(:year) # => 4
match.end('month') # => 7
Related: #byteend.
# File 're.c', line 1857
static VALUE
match_end(VALUE match, VALUE n)
{
int i = match_backref_number(match, n);
match_check(match);
backref_number_check(match, i);
if (RMATCH_BEG(match, i) < 0)
return Qnil;
update_char_offset(match);
return LEN2NUM(RMATCH(match)->char_offset[i].end);
}
#==(object) ⇒ Boolean
#eql?(object) ⇒ Boolean
Boolean
#eql?(object) ⇒ Boolean
Alias for #==.
#hash ⇒ Integer
Returns the integer hash value for self,
based on its target string, regexp, match, and captures.
See also Object#hash.
# File 're.c', line 4344
static VALUE
match_hash(VALUE match)
{
st_index_t hashval;
match_check(match);
hashval = rb_hash_start(rb_str_hash(RMATCH(match)->str));
hashval = rb_hash_uint(hashval, reg_hash(match_regexp(match)));
int num_regs = RMATCH_NREGS(match);
hashval = rb_hash_uint(hashval, num_regs);
hashval = rb_hash_uint(hashval, rb_memhash(RMATCH_BEG_PTR(match), num_regs * sizeof(OnigPosition)));
hashval = rb_hash_uint(hashval, rb_memhash(RMATCH_END_PTR(match), num_regs * sizeof(OnigPosition)));
hashval = rb_hash_end(hashval);
return ST2FIX(hashval);
}
#initialize_copy(orig)
# File 're.c', line 1356
VALUE
rb_match_init_copy(VALUE obj, VALUE orig)
{
struct RMatch *rm = RMATCH(obj);
if (!OBJ_INIT_COPY(obj, orig)) return obj;
RB_OBJ_WRITE(obj, &rm->str, RMATCH(orig)->str);
RB_OBJ_WRITE(obj, &rm->regexp, RMATCH(orig)->regexp);
match_set_regs(obj, RMATCH_NREGS(orig), RMATCH_BEG_PTR(orig), RMATCH_END_PTR(orig));
if (RMATCH(orig)->char_offset_num_allocated) {
if (rm->char_offset_num_allocated < rm->num_regs) {
SIZED_REALLOC_N(rm->char_offset, struct rmatch_offset, rm->num_regs, rm->char_offset_num_allocated);
rm->char_offset_num_allocated = rm->num_regs;
FL_SET_RAW(obj, RMATCH_OFFSETS_EXTERNAL);
}
MEMCPY(rm->char_offset, RMATCH(orig)->char_offset,
struct rmatch_offset, rm->num_regs);
RB_GC_GUARD(orig);
}
return obj;
}
#inspect ⇒ String
Returns a string representation of self:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
match.inspect # => "#<MatchData \"2026-12-25\" 1:\"2026\" 2:\"12\" 3:\"25\">"
match = /(ん)(に)(ち)/.match('こんにちは')
match.inspect # => "#<MatchData \"んにち\" 1:\"ん\" 2:\"に\" 3:\"ち\">"
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
match.inspect # => "#<MatchData \"2026-12-25\" year:\"2026\" month:\"12\" day:\"25\">"
Related: #to_s.
# File 're.c', line 3353
static VALUE
match_inspect(VALUE match)
{
VALUE cname = rb_class_path(rb_obj_class(match));
VALUE str;
int i;
int num_regs = RMATCH_NREGS(match);
struct backref_name_tag *names;
VALUE names_obj = Qnil;
VALUE regexp = RMATCH(match)->regexp;
if (regexp == 0) {
return rb_sprintf("#<%"PRIsVALUE":%p>", cname, (void*)match);
}
else if (NIL_P(regexp)) {
return rb_sprintf("#<%"PRIsVALUE": %"PRIsVALUE">",
cname, rb_reg_nth_match(0, match));
}
names = RB_ALLOCV_N(struct backref_name_tag, names_obj, num_regs);
MEMZERO(names, struct backref_name_tag, num_regs);
onig_foreach_name(RREGEXP_PTR(regexp),
match_inspect_name_iter, names);
str = rb_str_buf_new2("#<");
rb_str_append(str, cname);
for (i = 0; i < num_regs; i++) {
VALUE v;
rb_str_buf_cat2(str, " ");
if (0 < i) {
if (names[i].name)
rb_str_buf_cat(str, (const char *)names[i].name, names[i].len);
else {
rb_str_catf(str, "%d", i);
}
rb_str_buf_cat2(str, ":");
}
v = rb_reg_nth_match(i, match);
if (NIL_P(v))
rb_str_buf_cat2(str, "nil");
else
rb_str_buf_append(str, rb_str_inspect(v));
}
rb_str_buf_cat2(str, ">");
RB_ALLOCV_END(names_obj);
return str;
}
Returns a captured substring converted to an integer;
the substring is interpreted as a numeric string in the given radix.
With integer index n given,
returns the nth capture converted to an integer:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match[0] # => "2026-12-25"
match.integer_at(0) # => 2026 # Stops interpreting at the hyphen.
match.integer_at(1) # => 2026
match.integer_at(2) # => 12
match.integer_at(3) # => 25
match.integer_at(-1) # => 25 # For negative n, counts backwards in the captures.
match.integer_at(4) # => nil
With string or symbol name given,
returns the named capture converted to an integer:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match.integer_at(:year) # => 2026
match.integer_at('month') # => 12
match.integer_at(:nosuch) # Raises IndexError: undefined group name reference: nosuch.
Returns nil if there were no captures.
For both forms above, the string is converted in the given radix:
match = /\d+/.match('11')
#### => #<MatchData "11">
match.integer_at(0) # => 11
match.integer_at(0, 2) # => 3
match.integer_at(0, 8) # => 9
match.integer_at(0, 16) # => 17
match.integer_at(0, 1) # Raises ArgumentError: invalid radix 1.
Related: #[], String#to_i.
# File 're.c', line 4453
static VALUE
match_integer_at(int argc, VALUE *argv, VALUE match)
{
match_check(match);
int base = 10;
VALUE idx;
int nth;
argc = rb_check_arity(argc, 1, 2);
if (FIXNUM_P(idx = argv[0])) {
nth = NUM2INT(idx);
}
else if ((nth = namev_to_backref_number(match, idx)) < 0) {
name_to_backref_error(idx);
}
if (argc > 1 && (base = NUM2INT(argv[1])) < 0) {
rb_raise(rb_eArgError, "invalid radix %d", base);
}
if (nth >= RMATCH_NREGS(match)) return Qnil;
if (nth < 0 && (nth += RMATCH_NREGS(match)) <= 0) return Qnil;
rb_len_t start = RMATCH_BEG(match, nth), end = RMATCH_END(match, nth);
if (start < 0) return Qnil;
RUBY_ASSERT(start <= end, "%"PRIdLEN" > %"PRIdLEN, start, end);
VALUE str = RMATCH(match)->str;
RUBY_ASSERT(end <= RSTRING_LEN(str), "%"PRIdLEN" > %"PRIdLEN, end, RSTRING_LEN(str));
char *endp;
return rb_int_parse_cstr(RSTRING_PTR(str) + start, end - start, &endp, NULL,
base, RB_INT_PARSE_DEFAULT);
}
#length ⇒ Integer Also known as: #size
# File 're.c', line 1458
static VALUE
match_size(VALUE match)
{
match_check(match);
return INT2FIX(RMATCH_NREGS(match));
}
Returns the matched substring corresponding to the given argument.
With non-negative integer argument n given,
returns the matched substring for the nth match:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match.match(0) # => "2026-12-25"
match.match(1) # => "2026"
match.match(2) # => "12"
match.match(3) # => "25"
match.match(4) # Raises IndexError: index 4 out of matches.
Except for n == 0, these same values are available
in Regexp global variables:
$0 # Returns the name of the current program.
$1 # => "2026"
$2 # => "12"
$3 # => "25"
$4 # => nil
Returns nil for an optional capture that had no match:
match = /(\d)(?:-(\d))?/.match('123')
#### => #<MatchData "123" 1:"123" 2:nil>
match.match(0) # => "123"
match.match(1) # => "123"
match.match(2) # => nil
With string or symbol argument name given,
returns the matched substring for the given name:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match.match(:year) # => "2026"
match.match('day') # => "25"
match.match(:nosuch) # Raises IndexError: undefined group name reference: nosuch.
Returns nil for a named capture that had no match:
match = /(?<year>\d{4})(?:-(?<month>\d{2}))?/.match('2026')
#### => #<MatchData "2026" year:"2026" month:nil>
match.match(:year) # => "2026"
match.match(:month) # => nil
# File 're.c', line 1940
static VALUE
match_nth(VALUE match, VALUE n)
{
int i = match_backref_number(match, n);
backref_number_check(match, i);
rb_len_t start = RMATCH_BEG(match, i), end = RMATCH_END(match, i);
if (start < 0)
return Qnil;
return rb_str_subseq(RMATCH(match)->str, start, end - start);
}
Returns the length (in characters) of the matched substring corresponding to the given argument.
With non-negative integer argument n given,
returns the length of the matched substring
for the nth match:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match.match_length(0) # => 10
match.match_length(3) # => 2
match.match_length(4) # Raises IndexError: index 4 out of matches.
s = 'こんにちは' # Four 3-byte characters.
match = /(こん)(に)(ち)/.match(s)
#### => #<MatchData "こんにち" 1:"こん" 2:"に" 3:"ち">
match.match_length(0) # => 4
match.match_length(1) # => 2
match.match_length(3) # => 1
match.match_length(4) # Raises IndexError: index 4 out of matches.
With string or symbol argument name given,
returns the length of the matched substring
for the named match:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match.match_length(:year) # => 4
match.match_length('day') # => 2
match.match_length(:nosuch) # Raises IndexError: undefined group name reference: nosuch.
# File 're.c', line 2001
static VALUE
match_nth_length(VALUE match, VALUE n)
{
int i = match_backref_number(match, n);
match_check(match);
backref_number_check(match, i);
if (RMATCH_BEG(match, i) < 0)
return Qnil;
update_char_offset(match);
const struct rmatch_offset *const ofs =
&RMATCH(match)->char_offset[i];
return LEN2NUM(ofs->end - ofs->beg);
}
#named_captures(symbolize_names: false) ⇒ Hash
Returns a hash of capture names and values:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match.named_captures # => {"year" => "2026", "month" => "12", "day" => "25"}
With keyword argument symbolize_names given as true,
returns hash keys as symbols:
match.named_captures(symbolize_names: true)
#### => {year: "2026", month: "12", day: "25"}
Returns a nil hash value for a name that captured nothing:
regexp = /(?<year>\d{4})-(?<month>\d{2})?/
#### => /(?<year>\d{4})-(?<month>\d{2})?/
match = '2026-'.match(regexp)
#### => #<MatchData "2026-" year:"2026" month:nil>
match.named_captures # => {"year" => "2026", "month" => nil}
# File 're.c', line 3158
static VALUE
match_named_captures(int argc, VALUE *argv, VALUE match)
{
VALUE hash;
match_check(match);
if (NIL_P(RMATCH(match)->regexp))
return rb_hash_new();
VALUE opt;
int symbolize_names = 0;
rb_scan_args(argc, argv, "0:", &opt);
if (!NIL_P(opt)) {
static ID keyword_ids[1];
VALUE symbolize_names_val;
if (!keyword_ids[0]) {
keyword_ids[0] = rb_intern_const("symbolize_names");
}
rb_get_kwargs(opt, keyword_ids, 0, 1, &symbolize_names_val);
if (!UNDEF_P(symbolize_names_val) && RTEST(symbolize_names_val)) {
symbolize_names = 1;
}
}
hash = rb_hash_new();
struct named_captures_data data = { hash, match, symbolize_names };
onig_foreach_name(RREGEXP_PTR(RMATCH(match)->regexp), match_named_captures_iter, &data);
return hash;
}
#names ⇒ array_of_strings
# File 're.c', line 1432
static VALUE
match_names(VALUE match)
{
match_check(match);
if (NIL_P(RMATCH(match)->regexp))
return rb_ary_new_capa(0);
return rb_reg_names(RMATCH(match)->regexp);
}
Returns the offsets (in characters) of the beginning (#begin value) and end (#end value) of the specified match.
With non-negative integer argument n given,
returns the character offsets for the nth match:
regexp = /(\d{4})-(\d{2})-(\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
match[0] # => "2026-12-25"
match.offset(0) # => [0, 10]
match[2] # => "12"
match.offset(2) # => [5, 7]
match.offset(4) # Raises IndexError: index 4 out of matches.
match = /(ん)(に)(ち)/.match('こんにちは')
#### => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
match[0] # => "んにち"
match.offset(0) # => [1, 4]
match[2] # => "に"
match.offset(2) # => [2, 3]
match.offset(4) # Raises IndexError: index 4 out of matches.
With string or symbol argument name given,
returns the offsets for the named match:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match[:year] # => "2026"
match.offset(:year) # => [0, 4]
match['day'] # => "25"
match.offset('day') # => [8, 10]
match.offset(:nosuch) # Raises IndexError: undefined group name reference: nosuch.
# File 're.c', line 1558
static VALUE
match_offset(VALUE match, VALUE n)
{
int i = match_backref_number(match, n);
match_check(match);
backref_number_check(match, i);
if (RMATCH_BEG(match, i) < 0)
return rb_assoc_new(Qnil, Qnil);
update_char_offset(match);
return rb_assoc_new(LEN2NUM(RMATCH(match)->char_offset[i].beg),
LEN2NUM(RMATCH(match)->char_offset[i].end));
}
#post_match ⇒ String
# File 're.c', line 2573
VALUE
rb_reg_match_post(VALUE match)
{
VALUE str;
rb_len_t pos;
if (NIL_P(match)) return Qnil;
match_check(match);
if (RMATCH_BEG(match, 0) == -1) return Qnil;
str = RMATCH(match)->str;
pos = RMATCH_END(match, 0);
str = rb_str_subseq(str, pos, RSTRING_LEN(str) - pos);
return str;
}
#pre_match ⇒ String
# File 're.c', line 2541
VALUE
rb_reg_match_pre(VALUE match)
{
VALUE str;
if (NIL_P(match)) return Qnil;
match_check(match);
if (RMATCH_BEG(match, 0) == -1) return Qnil;
str = rb_str_subseq(RMATCH(match)->str, 0, RMATCH_BEG(match, 0));
return str;
}
#regexp ⇒ Regexp
# File 're.c', line 1401
static VALUE
match_regexp(VALUE match)
{
VALUE regexp;
match_check(match);
regexp = RMATCH(match)->regexp;
if (NIL_P(regexp)) {
VALUE str = rb_reg_nth_match(0, match);
regexp = rb_reg_regcomp(rb_reg_quote(str));
RB_OBJ_WRITE(match, &RMATCH(match)->regexp, regexp);
}
return regexp;
}
Alias for #length.
#string ⇒ String
# File 're.c', line 3303
static VALUE
match_string(VALUE match)
{
match_check(match);
return RMATCH(match)->str; /* str is frozen */
}
#to_a ⇒ Array
# File 're.c', line 2686
static VALUE
match_to_a(VALUE match)
{
return match_array(match, 0);
}
#to_s ⇒ String
# File 're.c', line 3074
static VALUE
match_to_s(VALUE match)
{
VALUE str = rb_reg_last_match(match_check(match));
if (NIL_P(str)) str = rb_str_new(0,0);
return str;
}
#values_at(*indexes) ⇒ Array
Returns an array of matched substrings as specified by the given indexes,
which may be any mixture of integers, names, and ranges.
For each integer index n,
includes the nth matched substring:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match.values_at(3, 1, 2, 0) # => ["25", "2026", "12", "2026-12-25"]
For negative n, counts backwards in the array of matched substrings:
match.values_at(3, -1) # => ["25", "25"]
For n out of range, returns nil:
match.values_at(4, -4) # => [nil, nil]
For each string or symbol index name,
includes the matched substring for that name:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match.values_at(:day, 'year') # => ["25", "2026"]
match.values_at(:nosuch) # Raises IndexError: undefined group name reference: nosuch.
For a Range index range,
returns the matched substrings for the indexes covered by that range:
regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = '2026-12-25'.match(regexp)
#### => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
match.values_at(1..2) # => ["2026", "12"]
match.values_at(1...3) # => ["2026", "12"]
For positive range value out-of-range, fills with nil:
match.values_at(1..5) # => ["2026", "12", "25", nil, nil]
For negative range value, counts backwards in the array of matched substrings:
match.values_at(-3..-1) # => ["2026", "12", "25"]
match.values_at(-5..-1) # Raises RangeError: -5..-1 out of range.
Mixed-type indexes:
match.values_at(:year, 1, :month, 2, :day, 3, 0..3)
#### => ["2026", "2026", "12", "12", "25", "25", "2026-12-25", "2026", "12", "25"]
# File 're.c', line 3029
static VALUE
match_values_at(int argc, VALUE *argv, VALUE match)
{
VALUE result;
int i;
match_check(match);
result = rb_ary_new2(argc);
for (i=0; i<argc; i++) {
if (FIXNUM_P(argv[i])) {
rb_ary_push(result, rb_reg_nth_match(FIX2INT(argv[i]), match));
}
else {
int num = namev_to_backref_number(match, argv[i]);
if (num >= 0) {
rb_ary_push(result, rb_reg_nth_match(num, match));
}
else {
match_ary_aref(match, argv[i], result);
}
}
}
return result;
}