How to Use Named Capture Groups in Ruby: Syntax and Examples
(?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 (? 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.
/(?<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.
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
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.
# 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"Quick Reference
| Feature | Syntax | Description |
|---|---|---|
| Named capture group | (? | Captures text with a name for easy access |
| Access by name | match[:name] | Get captured text by group name from MatchData |
| Check match | if match | Always verify match success before accessing groups |
| Invalid names | N/A | Names must start with a letter and contain only letters, digits, or underscores |