0Pricing
Ruby Academy · Lesson

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_captures

All lessons in this course

  1. Regex Literals
  2. Matching and Capturing
  3. Substitution
  4. Named Groups and Anchors
← Back to Ruby Academy