Named Groups and Anchors
Advanced regex.
Why Named Groups?
Numbered captures like m[1] become hard to read when a pattern grows. Named groups give each capture a meaningful label.
Syntax: (?<name>pattern).
m = /(?<year>\d{4})-(?<month>\d{2})/.match('2026-05')
puts(m[:year])
puts(m[:month])Accessing Named Captures
Access named captures with a Symbol or String key: m[:name]. The method named_captures returns them all as a Hash.
m = /(?<user>\w+)@(?<host>\w+)/.match('alice@mail')
p m.named_capturesAll lessons in this course
- Regex Literals
- Matching and Capturing
- Substitution
- Named Groups and Anchors