Regular Expressions
Anchors: \A/\z (start/end of string) vs ^/$ (start/end of line). Use \A/\z for validation (security).
Flags: i (ignore case), m (dot matches newline), x (extended), o (interpolate once).
Ruby uses the Onigmo engine: lookahead/lookbehind (?=), (?<=), atomic groups, possessive quantifiers, Unicode properties \p{L}.
text = "Order #A123 shipped on 2025-10-24 to [email protected]"
text =~ /\d{4}-\d{2}-\d{2}/ # index of the match (or nil)
text.match?(/shipped/) # boolean (fastest)
m = text.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)
m[:year]; m["month"]; m.pre_match; m.post_match; m.captures; m.named_captures
if text =~ /#(\w+)/
puts $1 # last match group (also $~, Regexp.last_match)
end
text.scan(/\d+/) # ["123", "2025", "10", "24"]
text.scan(/(\w+)@(\w+)/) # [["ana", "example"]]
text.gsub(/\d/, "#")
text.gsub(/(?<user>\w+)@/) { "#{$~[:user].upcase}@" }
text.sub(/order/i, "Invoice")
text.split(/\s+/)
text[/#(\w+)/, 1] # "A123"
email = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
"[email protected]".match?(email)
pattern = %r{https?://[\w./-]+}x # %r literal, x = extended (whitespace/comments allowed)
date_re = /
(?<y>\d{4}) - # year
(?<m>\d{2}) - # month
(?<d>\d{2}) # day
/x
if (md = date_re.match("2025-10-24")) then puts md[:y] end
Regexp.escape("a.b*c"); Regexp.union("cat", "dog"); /x/.source
Regexp.timeout = 1.0 # ReDoS protection (Ruby 3.2+)