Ruby regular expressions
last modified December 2, 2026
In this article we work with regular expressions in Ruby. We match patterns,
extract data with capture groups, replace text with sub and
gsub, split strings, and finish with parsing log lines and
validating input.
A regular expression is a pattern that describes a set of strings. Ruby has
them built into the language: a regex literal such as /falcon/
creates an object of the Regexp class, and many
String methods accept a regex wherever they accept a plain
string. The engine is Onigmo, which supports Perl-style syntax including named
groups and lookaround.
First match
The match? method tells whether a string contains the pattern.
The =~ operator returns the index where the first match starts,
or nil when there is none.
#!/usr/bin/env ruby
words = %w[sky cloud falcon forest cliff]
words.each do |word|
if word.match?(/f/)
puts "#{word} contains f"
end
end
puts "The cloud is white" =~ /cloud/
p "The sky is blue" =~ /cloud/
The /f/ pattern matches any word that contains the letter f.
match? returns true or false, so it fits
naturally in an if condition. =~ finds
cloud at index 4; the second string contains no match, so
p shows nil.
$ ./first_match.rb falcon contains f forest contains f cliff contains f 4 nil
Creating regular expressions
Besides the slash literal, a regex can be written with %r{} or
built from a string at runtime with Regexp.new. The
%r form is handy when the pattern contains slashes.
#!/usr/bin/env ruby
re1 = /falcon/
re2 = %r{/usr/bin/\w+}
re3 = Regexp.new("fal" + "con")
puts re1.class
puts re1 == re3
puts re1.source
puts "/usr/bin/ruby".match?(re2)
word = "falcon"
re4 = /a #{word}/
puts re4.inspect
price = "$9.99"
puts Regexp.escape(price)
puts "Total: $9.99" =~ Regexp.new(Regexp.escape(price))
All three forms create a Regexp; re1 and
re3 are equal because they have the same source. Inside a regex
literal, #{} interpolates a value just as in a double-quoted
string. When the value comes from outside and may contain special characters,
Regexp.escape turns them into literal characters; without it, the
$ and . in the price would act as an anchor and a
wildcard.
$ ./literals.rb Regexp true falcon true /a falcon/ \$9\.99 7
Character classes and quantifiers
A character class matches one character out of a set, and a quantifier says
how many times the preceding item repeats. The scan method
returns every match, which makes it a good tool for seeing what a pattern
matches.
#!/usr/bin/env ruby
text = "Room 12 opens at 9:30, room 104 at 14:05."
p text.scan(/\d/)
p text.scan(/\d+/)
p text.scan(/\d{3}/)
p text.scan(/\d{1,2}:\d{2}/)
p text.scan(/[Rr]oom/)
p text.scan(/[aeiou]{2}/)
p text.scan(/\w+/).first(4)
p text.scan(/[^\w\s]/)
p "colour color".scan(/colou?r/)
p "a ab abb abbb".scan(/ab*/)
\d is a digit, \w a word character (a letter, digit
or underscore) and \s a whitespace character. The quantifier
+ means one or more, * zero or more, ?
zero or one, and {1,2} one to two repetitions. Brackets define a
custom class such as [Rr], and a leading caret negates it:
[^\w\s] matches the punctuation.
$ ./classes.rb ["1", "2", "9", "3", "0", "1", "0", "4", "1", "4", "0", "5"] ["12", "9", "30", "104", "14", "05"] ["104"] ["9:30", "14:05"] ["Room", "room"] ["oo", "oo"] ["Room", "12", "opens", "at"] [":", ",", ":", "."] ["colour", "color"] ["a", "ab", "abb", "abbb"]
Anchors
Anchors match a position instead of a character. In Ruby, ^ and
$ match at the start and end of every line, not just the whole
string. To anchor the whole string, use \A and \z.
#!/usr/bin/env ruby puts "ruby".match?(/\Aruby\z/) puts "ruby!".match?(/\Aruby\z/) text = "first line\nruby line\nlast line" puts text.match?(/^ruby/) puts text.match?(/\Aruby/) p text.scan(/^\w+/) p text.scan(/\w+$/) input = "42\nrm -rf /" puts input.match?(/^\d+$/) puts input.match?(/\A\d+\z/) p "cat concat category".scan(/\bcat\b/) p "cat concat category".scan(/cat\b/)
/^ruby/ finds ruby at the start of the second line,
while /\Aruby/ fails because the string starts with
first. The difference matters for validation: /^\d+$/
accepts the input because its first line is a number, even though a shell
command follows. Always validate with \A and \z.
\b marks a word boundary, so /\bcat\b/ matches only
the whole word, while /cat\b/ also matches the end of
concat.
$ ./anchors.rb true false true false ["first", "ruby", "last"] ["line", "line", "line"] true false ["cat"] ["cat", "cat"]
MatchData and capture groups
Parentheses form a capture group. The match method returns a
MatchData object that holds the whole match and the text of each
group, or nil when the pattern does not match.
#!/usr/bin/env ruby
line = "Released on 2026-10-18 by the core team"
m = line.match(/(\d{4})-(\d{2})-(\d{2})/)
puts m.class
puts m[0]
puts m[1]
puts m[2]
puts m[3]
p m.captures
p m.pre_match
p m.post_match
puts m.begin(0)
p "no date here".match(/\d{4}/)
if line =~ /by the (\w+)/
puts $~[0]
puts $1
end
m[0] is the whole match and m[1] to
m[3] are the groups, numbered by their opening parentheses.
captures returns all groups as an array, and
pre_match and post_match hold the text around the
match. A successful =~ also sets global variables:
$~ is the last MatchData and $1 the
first group. match? does not set them, which makes it faster.
$ ./match_data.rb MatchData 2026-10-18 2026 10 18 ["2026", "10", "18"] "Released on " " by the core team" 12 nil by the core core
Named groups
The (?<name>...) syntax gives a group a name. Named groups
make a pattern self-documenting and let us read the values by name instead of
by position.
#!/usr/bin/env ruby
line = "Released on 2026-10-18 by the core team"
date_re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
m = line.match(date_re)
puts m[:year]
puts m["month"]
puts m[:day]
p m.names
p m.named_captures
if /(?<user>\w+)@(?<host>[\w.]+)/ =~ "Mail jan@example.com today"
puts user
puts host
end
The groups are read with a symbol or a string key, and
named_captures returns them as a hash. When a regex literal with
named groups stands on the left side of =~, Ruby assigns each
group to a local variable of the same name, here user and
host. This only works when the literal comes first; a variable
holding the regex or a regex on the right side creates no variables.
$ ./named_groups.rb
2026
10
18
["year", "month", "day"]
{"year"=>"2026", "month"=>"10", "day"=>"18"}
jan
example.com
Finding all matches with scan
We have used scan with simple patterns. When the pattern contains
groups, scan returns the captured text instead of the whole
match, one array per match.
#!/usr/bin/env ruby
text = "Prices: $12, $7 and $150"
p text.scan(/\$\d+/)
p text.scan(/\$(\d+)/)
p text.scan(/\$(\d+)/).flatten.map(&:to_i).sum
pairs = "width=800 height=600 depth=32"
p pairs.scan(/(\w+)=(\d+)/)
p pairs.scan(/(\w+)=(\d+)/).to_h
pairs.scan(/(\w+)=(\d+)/) do |key, value|
puts "#{key.ljust(6)} #{value.rjust(4)}"
end
With one group, each match becomes a one-element array, which
flatten removes. With two groups, scan produces
key-value pairs that to_h turns into a hash. The block form of
scan passes the groups of each match to the block.
$ ./scan_groups.rb
["$12", "$7", "$150"]
[["12"], ["7"], ["150"]]
169
[["width", "800"], ["height", "600"], ["depth", "32"]]
{"width"=>"800", "height"=>"600", "depth"=>"32"}
width 800
height 600
depth 32
Replacing text with sub and gsub
The sub method replaces the first match and gsub
replaces all of them. The replacement string can refer back to the groups of
the match.
#!/usr/bin/env ruby text = "the old falcon and the old owl" puts text.sub(/old/, "young") puts text.gsub(/old/, "young") puts text.gsub(/[aeiou]/, "*") puts "John Smith".sub(/(\w+) (\w+)/, '\2, \1') puts "2026-10-18".sub(/(\d+)-(\d+)-(\d+)/, '\3.\2.\1') puts "2026-10-18".sub(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/, '\k<d>/\k<m>/\k<y>') puts "falcon".gsub(/[aeiou]/, '[\0]') puts "cat and dog".gsub(/cat|dog/, "cat" => "kitten", "dog" => "puppy") name = "Jan" name.sub!(/an/, "ane") puts name
In a replacement string, \1 and \2 insert the
numbered groups, \k<d> a named group and \0
the whole match. We use single quotes so that the backslashes reach
sub unchanged. A hash as the second argument maps each matched
text to its replacement. The bang versions sub! and
gsub! modify the string in place.
$ ./sub_gsub.rb the young falcon and the old owl the young falcon and the young owl th* *ld f*lc*n *nd th* *ld *wl Smith, John 18.10.2026 18/10/2026 f[a]lc[o]n kitten and puppy Jane
Replacement blocks
When the replacement must be computed, sub and gsub
take a block. The block receives the matched text, its return value replaces
the match, and the groups are available in $1, $2 and
so on.
#!/usr/bin/env ruby
puts "snake_case_name".gsub(/_(\w)/) { $1.upcase }
puts "CamelCaseName".gsub(/([a-z])([A-Z])/) { "#{$1}_#{$2}" }.downcase
prices = "pen $2, book $15, lamp $40"
puts prices.gsub(/\$(\d+)/) { "$#{$1.to_i * 2}" }
puts "a1b22c333".gsub(/\d+/) { |num| "<#{num.length}>" }
counter = 0
puts "x x x".gsub(/x/) { counter += 1 }
text = "the quick brown fox"
puts text.gsub(/\w+/) { |word| word.capitalize }
puts text.gsub(/\b\w/, &:upcase)
The first two lines convert between snake case and camel case. The price line
does arithmetic on the captured number, which a replacement string cannot do.
The block may also keep state, as the counter shows. The last line passes
&:upcase instead of a block, which calls
upcase on every match.
$ ./gsub_block.rb snakeCaseName camel_case_name pen $4, book $30, lamp $80 a<1>b<2>c<3> 1 2 3 The Quick Brown Fox The Quick Brown Fox
Splitting strings
The split method accepts a regex as the separator. This lets us
split on several delimiters at once and swallow the whitespace around them.
#!/usr/bin/env ruby csv = "apple, banana;cherry ; date" p csv.split(/\s*[,;]\s*/) p "one1two22three333four".split(/\d+/) p "a b\tc\n d".split(/\s+/) p "2026-10-18T10:15:02".split(/[-T:]/).map(&:to_i) p "a,b;c".split(/([,;])/) p "one, two, three, four".split(/,\s*/, 2)
The first pattern treats commas and semicolons with any surrounding spaces as one separator. When the separator pattern has a group, the matched separators are kept in the result. The second argument limits the number of parts; the rest of the string stays in the last element.
$ ./split_re.rb ["apple", "banana", "cherry", "date"] ["one", "two", "three", "four"] ["a", "b", "c", "d"] [2026, 10, 18, 10, 15, 2] ["a", ",", "b", ";", "c"] ["one", "two, three, four"]
Flags
Flags written after the closing slash change how the pattern is interpreted.
Ruby has three: i ignores case, m lets the dot match
a newline and x enables extended mode.
#!/usr/bin/env ruby
p "Ruby RUBY ruby".scan(/ruby/i)
block = "<p>\nfirst\n</p>"
p block[/<p>.*<\/p>/]
p block[/<p>.*<\/p>/m]
phone = /
\A
\(?(\d{3})\)? # area code, optional parentheses
[-\s]? # optional separator
(\d{3}) # prefix
-(\d{4}) # line number
\z
/x
puts "(555) 123-4567".match?(phone)
puts "555-123-4567".match?(phone)
puts "555-123-456".match?(phone)
re = Regexp.new("r u b y", Regexp::IGNORECASE | Regexp::EXTENDED)
p re
p "RUBY".match?(re)
p "A RUBY gem".match?(/(?i)ruby/)
Without m, the dot stops at the newline and the slice returns
nil. Note that Ruby's m means what other languages
call the single-line or dotall mode; multiline anchors need no flag because
^ and $ always work per line. In extended mode,
whitespace is ignored and # starts a comment, so a long pattern
can be spread over lines. Regexp.new takes the flags as
constants, and (?i) switches a flag on inside the pattern.
$ ./flags.rb ["Ruby", "RUBY", "ruby"] nil "<p>\nfirst\n</p>" true true false /r u b y/ix true true
Greedy and lazy quantifiers
Quantifiers are greedy: they match as much text as possible while the rest of
the pattern can still match. Adding ? after a quantifier makes it
lazy, so it matches as little as possible.
#!/usr/bin/env ruby
html = "<b>bold</b> and <i>italic</i>"
p html.scan(/<.+>/)
p html.scan(/<.+?>/)
p html[/<(.*)>/, 1]
p html[/<(.*?)>/, 1]
text = 'say "one" and "two"'
p text.scan(/"(.*)"/)
p text.scan(/"(.*?)"/)
p text.scan(/"([^"]*)"/)
p "aaaa"[/a{2,3}/]
p "aaaa"[/a{2,3}?/]
The greedy <.+> runs from the first < to
the last > and swallows the whole string, while the lazy
<.+?> stops at the first > and finds each
tag. The str[re, 1] form returns the first group of the match.
A negated class such as [^"]* is often clearer than a lazy
quantifier, because it states exactly what may appear between the quotes.
The same applies to counted repetition: a{2,3} takes three
letters, a{2,3}? only two.
$ ./greedy.rb ["<b>bold</b> and <i>italic</i>"] ["<b>", "</b>", "<i>", "</i>"] "b>bold</b> and <i>italic</i" "b" [["one\" and \"two"]] [["one"], ["two"]] [["one"], ["two"]] "aaa" "aa"
Lookahead and lookbehind
Lookaround checks what comes before or after the current position without
including it in the match. (?=...) is a lookahead,
(?<=...) a lookbehind, and (?!...) and
(?<!...) are their negative forms.
#!/usr/bin/env ruby
prices = "USD100 EUR85 USD42 GBP70"
p prices.scan(/(?<=USD)\d+/)
p prices.scan(/[A-Z]{3}(?=\d{3})/)
p prices.scan(/\b(?!USD)[A-Z]{3}\d+/)
p prices.scan(/(?<=[A-Z]{3})(?<!USD)\d+/)
p "10000000 and 999".gsub(/\B(?=(\d{3})+\b)/, ",")
password = "Secret42"
strong = /\A(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}\z/
puts password.match?(strong)
puts "secret42".match?(strong)
(?<=USD)\d+ returns the amounts that follow USD without the
currency code. The negative lookahead (?!USD) skips the USD
entries, and the combined lookbehinds pick the amounts that follow a code
other than USD. The gsub inserts a comma at every position that
is followed by a multiple of three digits. The password pattern uses three
lookaheads at the start of the string, each requiring one kind of character
somewhere in it.
$ ./lookaround.rb ["100", "42"] ["USD"] ["EUR85", "GBP70"] ["85", "70"] "10,000,000 and 999" true false
Parsing log lines
Now we combine anchors, named groups and the x flag to parse log
lines. Lines that do not fit the format are reported and skipped.
#!/usr/bin/env ruby
LOG_LINE = /
\A
(?<date>\d{4}-\d{2}-\d{2})\s
(?<time>\d{2}:\d{2}:\d{2})\s
(?<level>[A-Z]+)\s
(?<msg>.+)
\z
/x
logs = [
"2026-10-18 10:15:02 ERROR Disk full on /dev/sda1",
"2026-10-18 10:16:44 INFO User alice logged in",
"garbage line without a timestamp",
"2026-10-18 10:17:09 WARN Memory at 91%",
"2026-10-18 10:21:30 ERROR Timeout talking to db01"
]
counts = Hash.new(0)
logs.each do |line|
m = LOG_LINE.match(line)
unless m
puts "skipped: #{line.inspect}"
next
end
counts[m[:level]] += 1
puts "#{m[:time]} [#{m[:level].ljust(5)}] #{m[:msg]}"
end
hosts = logs.join("\n").scan(/\b[a-z]+\d+\b/)
p counts
p hosts
The LOG_LINE pattern describes the whole line field by field,
and the \A and \z anchors reject lines with
anything extra. Hash.new(0) counts the lines per level. The
final scan collects host and device names, words that end with a
number, from all lines.
$ ./parse_log.rb
10:15:02 [ERROR] Disk full on /dev/sda1
10:16:44 [INFO ] User alice logged in
skipped: "garbage line without a timestamp"
10:17:09 [WARN ] Memory at 91%
10:21:30 [ERROR] Timeout talking to db01
{"ERROR"=>2, "INFO"=>1, "WARN"=>1}
["sda1", "db01"]
Validating input
A validation pattern must describe the entire input, so each rule is anchored
with \A and \z. The program checks sample values
against a table of rules.
#!/usr/bin/env ruby
RULES = {
"zip code" => /\A\d{5}(-\d{4})?\z/,
"email" => /\A[\w.+-]+@[\w-]+(\.[\w-]+)*\.[a-z]{2,}\z/i,
"time" => /\A([01]\d|2[0-3]):[0-5]\d\z/,
"hex colour" => /\A#(\h{3}|\h{6})\z/,
}
samples = {
"zip code" => ["94043", "94043-1351", "9404", "94043-13"],
"email" => ["jan@example.com", "x.y+z@mail.co.uk", "bad@", "a@b.c"],
"time" => ["09:30", "23:59", "24:00", "7:15"],
"hex colour" => ["#fff", "#1aa3ff", "#ggg", "1aa3ff"],
}
samples.each do |kind, values|
re = RULES[kind]
results = values.map { |v| "#{v} #{v.match?(re) ? 'ok' : 'bad'}" }
puts "#{kind.ljust(10)} #{results.join(', ')}"
end
The zip code allows an optional four-digit extension. The time rule limits
hours to 00–23 and minutes to 00–59. \h is a
hexadecimal digit, so the colour accepts three or six of them after the hash
sign. The email rule is a practical approximation; the full address grammar
is too complex for a readable regex, and the real test is sending a
message.
$ ./validate.rb zip code 94043 ok, 94043-1351 ok, 9404 bad, 94043-13 bad email jan@example.com ok, x.y+z@mail.co.uk ok, bad@ bad, a@b.c bad time 09:30 ok, 23:59 ok, 24:00 bad, 7:15 bad hex colour #fff ok, #1aa3ff ok, #ggg bad, 1aa3ff bad
Source
Ruby documentation: class Regexp
Ruby documentation: class MatchData
Ruby documentation: class String
In this article we have worked with regular expressions in Ruby. The string methods used alongside them are covered in Ruby strings; reading the lines of a real log file is shown in Ruby read file.
Author
List all Ruby tutorials.