0
0
RubyHow-ToBeginner · 3 min read

How to Use Named Capture Groups in Ruby: Syntax and Examples

In Ruby, you use named capture groups in regular expressions by enclosing the group pattern in (?pattern). You can then access the captured parts by name using MatchData#[] or named variables from the match result.
📐

Syntax

Named capture groups in Ruby use the syntax (?pattern) inside a regular expression. Here, name is the identifier you assign to the group, and pattern is the regex pattern you want to capture.

When you match a string, Ruby stores the captured text under that name, making it easy to access later.

ruby
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
💻

Example

This example shows how to extract year, month, and day from a date string using named capture groups. It demonstrates accessing the captured parts by their names.

ruby
date = "2024-06-15"
regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match = regex.match(date)

if match
  puts "Year: #{match[:year]}"
  puts "Month: #{match[:month]}"
  puts "Day: #{match[:day]}"
else
  puts "No match found"
end
Output
Year: 2024 Month: 06 Day: 15
⚠️

Common Pitfalls

One common mistake is forgetting the ?<name> syntax and using regular parentheses () which create unnamed capture groups. Another is trying to access named groups without checking if the match succeeded, which can cause errors.

Also, using invalid group names (like starting with a number or using special characters) will cause a syntax error.

ruby
# Wrong: unnamed groups
regex_wrong = /(\d{4})-(\d{2})-(\d{2})/
match_wrong = regex_wrong.match("2024-06-15")
puts match_wrong[:year] # => nil, no named group

# Right: named groups
regex_right = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
match_right = regex_right.match("2024-06-15")
puts match_right[:year] # => "2024"
Output
nil 2024
📊

Quick Reference

FeatureSyntaxDescription
Named capture group(?pattern)Captures text with a name for easy access
Access by namematch[:name]Get captured text by group name from MatchData
Check matchif matchAlways verify match success before accessing groups
Invalid namesN/ANames must start with a letter and contain only letters, digits, or underscores

Key Takeaways

Use (?pattern) to create named capture groups in Ruby regex.
Access captured groups by name using match[:name] for clear and readable code.
Always check if the regex match succeeded before accessing named groups.
Named group names must start with a letter and contain only letters, digits, or underscores.
Unnamed groups use regular parentheses () and do not support named access.