0Pricing
Ruby Academy · Lesson

Matching and Capturing

match and captures.

MatchData Objects

When you call regex.match(string) Ruby returns a MatchData object on success, or nil on failure.

MatchData holds the matched text and any captured groups.

m = /world/.match('hello world')
puts m.class
puts(m[0])

The Whole Match: index 0

Index 0 of a MatchData is always the entire matched substring, regardless of any groups.

m = /\d+/.match('order 4521 shipped')
puts(m[0])
puts(m.to_s)

All lessons in this course

  1. Regex Literals
  2. Matching and Capturing
  3. Substitution
  4. Named Groups and Anchors
← Back to Ruby Academy