0
0
Rubyprogramming~5 mins

Capture groups in Ruby

Choose your learning style9 modes available
Introduction

Capture groups help you find and save parts of text that match a pattern. You can use these saved parts later in your program.

Extracting a phone number from a text message.
Getting the username from an email address.
Finding dates in a document to use them separately.
Splitting a full name into first and last names.
Syntax
Ruby
/(pattern)/

Parentheses () create a capture group around the pattern inside.

You can access captured parts using special variables or methods.

Examples
This example captures parts of a phone number and prints each part separately.
Ruby
text = "My phone is 123-456-7890"
if text =~ /(\d{3})-(\d{3})-(\d{4})/
  puts "Area code: #{Regexp.last_match(1)}"
  puts "First three digits: #{Regexp.last_match(2)}"
  puts "Last four digits: #{Regexp.last_match(3)}"
end
This example captures the username and domain from an email address.
Ruby
email = "user@example.com"
if email =~ /(.+)@(.+)/
  username = Regexp.last_match(1)
  domain = Regexp.last_match(2)
  puts "Username: #{username}"
  puts "Domain: #{domain}"
end
Sample Program

This program finds a date in the text and prints the year, month, and day separately using capture groups.

Ruby
text = "Order number: 2024-06-15"
if text =~ /Order number: (\d{4})-(\d{2})-(\d{2})/
  year = Regexp.last_match(1)
  month = Regexp.last_match(2)
  day = Regexp.last_match(3)
  puts "Year: #{year}"
  puts "Month: #{month}"
  puts "Day: #{day}"
else
  puts "No date found."
end
OutputSuccess
Important Notes

Capture groups are numbered from left to right starting at 1.

You can use Regexp.last_match(n) to get the nth captured group.

If the pattern does not match, capture groups will be nil, so always check if the match succeeded.

Summary

Capture groups save parts of matched text for later use.

Use parentheses () to create capture groups in Ruby regex.

Access captured parts with Regexp.last_match(n).