String#match

str.match(pattern) -> MatchData or nil
Returns: MatchData or nil · Updated March 14, 2026 · String Methods
strings regex pattern-matching

The match method searches a string for a pattern match. It returns a MatchData object on success or nil if no match is found. For simple boolean checks, use match? which is faster and returns true or false.

Syntax

str.match(pattern)
str.match(pattern, index)

Parameters

ParameterTypeDefaultDescription
patternRegexp or StringThe pattern to search for. Strings are converted to Regexp.
indexInteger0Start position in the string to begin searching.

Examples

Basic regex matching

text = "Hello, World!"
result = text.match(/World/)

result[0]       # => "World"
result.begin(0) # => 7
result.end(0)   # => 12

Capturing groups

date = "2026-03-09"
match = date.match(/(\d{4})-(\d{2})-(\d{2})/)

match[0]   # => "2026-03-09"  (full match)
match[1]   # => "2026"        (first group)
match[2]   # => "03"          (second group)
match[3]   # => "09"          (third group)
match.captures  # => ["2026", "03", "09"]

Using match? for boolean checks

email = "user@example.com"

email.match?(/\w+@\w+\.\w+/)  # => true
email.match?(/^\d+$/)            # => false

# match? is faster when you only need true/false
if email.match?(/@/)
  puts "Has @ symbol"
end

Finding named captures

text = "Name: Ada"
match = text.match(/Name: (?<name>\w+)/)

match[:name]      # => "Ada"
match["name"]   # => "Ada"
match.captures    # => ["Ada"]

Start position parameter

text = "hello hello"
match1 = text.match(/hello/)
match2 = text.match(/hello/, match1.end(0))

match1[0]  # => "hello"
match2[0]  # => "hello" (second occurrence)

Common Patterns

Validation with captures

def extract_phone(text)
  match = text.match(/(\d{3})-(\d{3})-(\d{4})/)
  return nil unless match
  
  { area: match[1], prefix: match[2], line: match[3] }
end

extract_phone("Call me at 555-123-4567")
# => { area: "555", prefix: "123", line: "4567" }

Iterative matching with block

text = "one1 two2 three3"
results = []

text.scan(/\d+/) { |m| results << m }
results  # => ["1", "2", "3"]

Safe parsing

def parse_version(header)
  match = header.match(/Ruby (\d+\.\d+)/)
  match ? match[1] : nil
end

parse_version("Using Ruby 3.4")  # => "3.4"
parse_version("No version here") # => nil

See Also