class MatchData
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
Regexpused 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 $~:
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 aseql?): returns whetherselfand another object are equal. -
hash: returns the integer hash value forself. -
inspect: returns a string representation ofself. -
post_match: returns the substring that follows the matched string. -
pre_match: returns the substring that precedes the matched string. -
size(aliased aslength): returns the size of the array of matched substrings. -
string: returns the string used to produceself. -
to_a: returns the array of matched substrings. -
to_s: returns a string representation ofself.
Capture Methods
Each of these methods returns information about all captures:
-
captures(aliased asdeconstruct): 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.
Public Instance Methods
(MatchData other) → bool
(untyped) → false
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
(capture backref, ?nil) → String
(int start, int length) → Array[String?]
(range[int?] range) → Array[String?]
Source
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);
}
}
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"]
Source
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 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: MatchData#bytebegin.
Source
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 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: MatchData#begin.
Source
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));
}
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: MatchData#bytebegin.
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)));
}
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: MatchData#offset.
static VALUE
match_captures(VALUE match)
{
return match_array(match, 1);
}
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: MatchData.to_a.
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;
}
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) # => {}
Source
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);
}
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: MatchData#byteend.
Source
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;
}
() → Integer
Source
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);
}
Returns the integer hash value for self, based on its target string, regexp, match, and captures.
See also Object#hash.
() → String
Source
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 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: MatchData#to_s.
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);
}
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: MatchData#[], String#to_i.
Source
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 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
Source
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);
}
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.
() → Hash[String, String?]
(symbolize_names: true) → Hash[Symbol, String?]
(symbolize_names: boolish) → Hash[String | Symbol, String?]
Source
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;
}
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}
Source
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 an array containing the capture 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.names # => ["year", "month", "day"]
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));
}
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.
Source
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;
}
Returns the substring of the target string that follows the matched substring; equivalent to Regexp global variable $':
match = /\d+/.match('foo 123 bar 456') # => #<MatchData "123"> match.match(0) # => "123" match.post_match # => " bar 456"
() → String
Source
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;
}
Returns the substring of the target string that precedes the matched substring; equivalent to Regexp global variable $`:
match = /\d+/.match('foo 123 bar 456') # => #<MatchData "123"> match.match(0) # => "123" match.pre_match # => "foo "
() → Regexp
Source
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;
}
Returns the Regexp that produced the 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.regexp # => /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
() → Integer
Source
static VALUE
match_size(VALUE match)
{
match_check(match);
return INT2FIX(RMATCH_NREGS(match));
}
Returns size of the match array:
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.size # => 4
() → String
Source
static VALUE
match_string(VALUE match)
{
match_check(match);
return RMATCH(match)->str; /* str is frozen */
}
Returns the target string if it was frozen; otherwise, returns a frozen copy of the target string:
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.string # => "2026-12-25"
static VALUE
match_to_a(VALUE match)
{
return match_array(match, 0);
}
Returns the array of matched substrings:
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.to_a # => ["2026-12-25", "2026", "12", "25"]
() → String
Source
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;
}
Returns the matched substring; equivalent to match(0):
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.to_s # => "2026-12-25"
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;
}
Returns match and captures at the given indexes, which may include any mixture of:
-
Integers.
-
Ranges.
-
Names (strings and symbols).
Examples:
m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie") # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8"> m.values_at(0, 2, -2) # => ["HX1138", "X", "113"] m.values_at(1..2, -1) # => ["H", "X", "8"] m = /(?<a>\d+) *(?<op>[+\-*\/]) *(?<b>\d+)/.match("1 + 2") # => #<MatchData "1 + 2" a:"1" op:"+" b:"2"> m.values_at(0, 1..2, :a, :b, :op) # => ["1 + 2", "1", "+", "1", "2", "+"]