class MatchData

Ruby matcher methods create MatchData objects.

A MatchData object contains the detailed result of a match, including:

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 $~:

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: