0
0
Rubyprogramming~5 mins

Named captures in Ruby

Choose your learning style9 modes available
Introduction

Named captures help you find parts of text and give them easy names. This makes your code clearer and easier to use.

You want to get a person's first and last name separately from a full name string.
You need to extract the day, month, and year from a date in text.
You want to find and label parts of a phone number like area code and number.
You are parsing a log file and want to name parts like time and message.
Syntax
Ruby
/(?<name>pattern)/

The ?<name> inside the parentheses gives a name to the captured part.

You can access the named parts by their names instead of numbers.

Examples
This finds first and last names and prints them using their names.
Ruby
text = "John Doe"
if text =~ /(?<first>\w+) (?<last>\w+)/
  puts "First name: #{Regexp.last_match[:first]}"
  puts "Last name: #{Regexp.last_match[:last]}"
end
This extracts year, month, and day from a date string.
Ruby
date = "2024-06-15"
if date =~ /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
  puts "Year: #{Regexp.last_match[:year]}"
  puts "Month: #{Regexp.last_match[:month]}"
  puts "Day: #{Regexp.last_match[:day]}"
end
Sample Program

This program finds the first and last name in the text and prints them clearly using named captures.

Ruby
text = "Alice Wonderland"
if text =~ /(?<first>\w+) (?<last>\w+)/
  puts "First name: #{Regexp.last_match[:first]}"
  puts "Last name: #{Regexp.last_match[:last]}"
else
  puts "No match found."
end
OutputSuccess
Important Notes

You can use Regexp.last_match[:name] or match_data[:name] to get the named capture.

Named captures make your code easier to read than using numbers like match[1], match[2].

Summary

Named captures let you label parts of a matched text with easy names.

This helps you get parts of text clearly and simply.

Use ?<name> inside your regex to name a capture group.