Regular expressions for pattern matching

Sarah Mitchell Feb 2026
3 tabs
# Basic matching
email = "user@example.com"
email =~ /@/  # => 4 (position of match)
email.match?(/@/)  # => true

# Capture groups
match = email.match(/(.+)@(.+)\.(.+)/)
match[1]  # => "user"
match[2]  # => "example"
match[3]  # => "com"

# Named captures
match = email.match(/(?<user>.+)@(?<domain>.+)\.(?<tld>.+)/)
match[:user]    # => "user"
match[:domain]  # => "example"
match[:tld]     # => "com"

# Scan - find all matches
text = "My phone is 555-1234 and backup is 555-5678"
phones = text.scan(/\d{3}-\d{4}/)
# => ["555-1234", "555-5678"]

# Scan with groups
text = "Alice: 25, Bob: 30, Charlie: 35"
text.scan(/(\w+): (\d+)/)
# => [["Alice", "25"], ["Bob", "30"], ["Charlie", "35"]]

# gsub - global substitution
text = "Hello World"
text.gsub(/[aeiou]/, '*')  # => "H*ll* W*rld"
text.gsub(/\w+/) { |word| word.capitalize }  # => "Hello World"

# gsub with named captures
date = "2026-02-02"
date.gsub(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/) do |match|
  "#{$~[:month]}/#{$~[:day]}/#{$~[:year]}"
end
# => "02/02/2026"

# sub - single substitution
text.sub(/World/, 'Ruby')  # => "Hello Ruby"

# Split with regex
"one,two;three:four".split(/[,;:]/)
# => ["one", "two", "three", "four"]
3 files · ruby Explain with highlit

Ruby's regex engine provides powerful text processing. I use =~ for matching, match for captures. Character classes \d, \w, \s match digits, words, whitespace. Quantifiers *, +, ?, {n,m} control repetition. Anchors ^ and $ match start/end. Groups () capture subpatterns; (?:) for non-capturing groups. Named captures (?<name>) improve readability. Lookaheads (?=) and lookbehinds (?<=) assert without consuming. scan finds all matches; gsub replaces patterns. Regex literals // and %r{} allow different delimiters. Understanding regex enables text validation, parsing, and transformation. I balance regex power with readability—complex patterns need comments or extraction into methods.