Ruby example

How to find all regex matches in Ruby

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use scan: text.scan(/\d+/) returns an array of every matched string. When the pattern has groups, it returns one array of captures per match instead, so use (?:…) for groups you don't want back. For the first match only, use match (a MatchData or nil) or match? (true or false).

Ruby's regex methods live on String: scan finds every match, match, match? and =~ find the first one, and gsub replaces them all. The sections below cover scan with and without groups, getting each match's position as a MatchData, the first-match methods and named groups, why ^ and $ are the wrong anchors for validation in Ruby, putting a variable into a pattern safely, and the m, i and x flags, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1Every match: String#scanRecommended

scan walks the string left to right and collects every non-overlapping match. What it collects depends on the pattern: with no groups you get an array of strings; with groups you get an array of arrays, one per match, holding only the groups (named groups give the same shape). That catches people who add a group just for an alternation like (c|b)at: write it as a non-capturing (?:c|b)at or a character class to get whole matches back. Python readers: this is re.findall, with the same rule for groups.

scan.rb
text = "Order 12 shipped, order 345 pending, order 6 lost"

# No groups: an array of the matched strings
p text.scan(/\d+/)

# With groups: one array of captures per match
p text.scan(/order (\d+) (\w+)/i)

# Named groups give the same shape
p text.scan(/order (?<id>\d+) (?<status>\w+)/i)

# A group you only need for | changes the result too
p "cat bat rat".scan(/(c|b)at/)
p "cat bat rat".scan(/(?:c|b)at/)

# Pairs of groups turn straight into a hash
pairs = "a=1, b=22, c=333".scan(/(\w+)=(\d+)/)
p pairs.to_h.transform_values(&:to_i)

# With a block, scan yields each match instead
"x=1 y=2".scan(/(\w)=(\d)/) { |key, value| puts "#{key} is #{value}" }

# No match: an empty array, never nil
p text.scan(/xyz/)
p text.scan(/\d+/).size

Output

The first line is ["12", "345", "6"]; add groups and the same text gives [["12", "shipped"], …], and named groups lose their names in the result. (c|b)at returns [["c"], ["b"]], only the group, while (?:c|b)at returns ["cat", "bat"]. A miss returns [], so scan(re).size is a safe match count. Matches never overlap: "aaaa".scan(/aa/) finds two, not three.

2Positions and named groups: MatchData for every match

scan returns strings, which lose where each match was and which name each group had. To get a full MatchData per match (like Python's re.finditer or JavaScript's matchAll), turn scan into an enumerator with to_enum(:scan, re) and read Regexp.last_match inside map: scan sets it for each match. The older idiom does the same with gsub and a block, reading $~ (another name for Regexp.last_match) and throwing away the replaced string. Inside a scan block, $~, $& (the whole match) and $1, $2 work too.

match_data.rb
log = "GET /home 200, POST /login 401, GET /admin 403"
re = /(?<verb>GET|POST) (?<path>\S+) (?<code>\d{3})/

# Every match as a MatchData, with positions
matches = log.to_enum(:scan, re).map { Regexp.last_match }

matches.each do |m|
  puts "#{m[:verb]} #{m[:path]} -> #{m[:code]} at #{m.begin(0)}"
end
p matches.last
p matches.first.named_captures
p matches.map { |m| m.offset(:path) }

# Same result with gsub and a block, reading $~
found = []
log.gsub(re) { found << $~ }
p found.map { |m| m[:code] }

# scan with a block also sets $~ (and $&, $1, $2 ...)
log.scan(/\d{3}/) { puts "#{$&} at #{$~.begin(0)}" }

Output

Each MatchData keeps its groups by name (m[:verb]) and its position: begin(0) is where the whole match starts (0, 15, 32), and offset(:path) gives the start and end of one group, such as [4, 9] for /home. named_captures turns a match into a hash with string keys. The gsub version collects the same three matches; it builds a new string nobody uses, so prefer to_enum(:scan, re) in new code.

3The first match only: match, match? and =~

When one match is enough, match returns a MatchData or nil, match? returns true or false and is the fastest because it builds nothing and leaves $~ alone, and =~ returns the index where the match starts or nil. str[re] is a short way to get the matched text, or one group with a second argument. One quirk of =~: when a regex literal with named groups stands on its left, Ruby creates local variables named after the groups. A regex in a variable, or the string on the left, does not.

first_match.rb
date = "Released on 2026-12-02, patched 2027-01-15"

# match returns a MatchData for the first match, or nil
m = date.match(/(?<year>\d{4})-(?<month>\d\d)-(?<day>\d\d)/)
p m[0]
p m[:year]
p m["month"]
p m.pre_match
p date.match(/\d{5}/)

# match? only answers yes or no (and sets no $~)
p date.match?(/\d{4}/)

# =~ returns the index of the first match, or nil
p date =~ /\d/
p(/xyz/ =~ date)

# A literal regex with named groups on the LEFT of =~
# creates local variables
if /(?<year>\d{4})-(?<month>\d\d)/ =~ date
  puts "year=#{year} month=#{month}"
end

# Not with a regex held in a variable
re = /(?<day>\d\d)$/
re =~ date
p defined?(day)

# String#[] with a regex: the first match, or one group
p date[/\d{4}-\d\d-\d\d/]
p date[/(\d{4})-(\d\d)/, 2]
p date[/(?<year>\d{4})/, "year"]
p date[/xyz/]

Output

All of these stop at the first date, 2026-12-02; the second one is only reachable with scan. =~ prints 12, the index of the first digit, and nil on a miss, so it works in an if but is not a boolean. The if line prints year=2026 month=12 through the variables =~ created, while defined?(day) prints nil because that regex sat in a variable. Coming from JavaScript: Ruby has no g flag, so match always stops at the first match and scan is how you get all of them.

4Anchors: \A and \z, not ^ and $

In Ruby, ^ and $ always match at the start and end of every line, not of the whole string. Most languages do that only with a multiline flag (Python's re.M, JavaScript's m); Ruby has no way to turn it off. So a validation written as /^[a-z0-9]+$/ accepts any input whose first line is valid, whatever follows the newline. Anchor validations with \A (start of string) and \z (end of string). \Z also allows one trailing newline, which is rarely what a validation wants. Rails' validates format: raises an error when the pattern uses ^ or $ unless you pass multiline: true.

anchors.rb
# Meant to allow only a username of letters and digits
loose  = /^[a-z0-9]+$/
strict = /\A[a-z0-9]+\z/

input = "alice\n<script>alert(1)</script>"

p input.match?(loose)
p input.match?(strict)
p "alice".match?(strict)

# ^ and $ match at the start and end of EVERY line
p "one\ntwo\nthree".scan(/^\w+$/)
p "one\ntwo\nthree".scan(/\A\w+/)

# \Z allows one trailing newline, \z allows nothing after
p "alice\n".match?(/\A[a-z]+\Z/)
p "alice\n".match?(/\A[a-z]+\z/)
p "alice\n".chomp.match?(/\A[a-z]+\z/)

Output

The loose pattern prints true for a username followed by a newline and a script tag: ^ and $ matched around alice on the first line, and the rest of the input was never checked. The \A…\z version rejects it and still accepts "alice". The same rule is useful in scan: /^\w+$/ finds all three lines. \Z accepts "alice\n" and \z does not, so either strip input with chomp first or keep \z and reject it.

5A variable in a pattern: Regexp.escape and Regexp.union

/#{x}/ interpolates a string into a regex literal, but the string is read as regex syntax: a . matches any character, + and ? are quantifiers, and an unbalanced ( raises RegexpError at run time. When the string is meant literally, wrap it in Regexp.escape (also named Regexp.quote). For several literal strings, Regexp.union escapes each one and joins them with |. Regexp.new(str) builds a regex from a string and needs the same escaping.

escape_variable.rb
text = "Total: 3750 or 3.50"
price = "3.50"

# Interpolated as-is, the dot means "any character"
p text.scan(/#{price}/)
p text.scan(/#{Regexp.escape(price)}/)
p Regexp.escape(price)

# + and ( are regex syntax too
term = "c++"
p "I write c++ and cc".scan(/#{term}/)
p "I write c++ and cc".scan(/#{Regexp.escape(term)}/)

name = "f(x"
begin
  /#{name}/
rescue RegexpError => e
  puts "#{e.class}: #{e.message}"
end

# Regexp.union escapes each string and joins them with |
re = Regexp.union("cat", "c++", "1.5")
p re
p "cat c++ 1.5 1x5".scan(re)

# Whole words only, ignoring case
word = "cat"
p "Cat concat cats CAT".scan(/\b#{Regexp.escape(word)}\b/i)

# A Regexp object keeps its own flags when interpolated
p(/#{Regexp.union("cat")}/i)
p "Cat".match?(/#{Regexp.union("cat")}/i)

Output

Unescaped, 3.50 also matches 3750, and c++ becomes a quantifier that finds ["c", "cc"] and never the plus signs; escaped, each finds only itself. p shows the escaped string as "3\\.50" because inspect doubles the backslash; the string holds one. f(x fails with RegexpError: end pattern with unmatched parenthesis, so escape anything that comes from a user. The last two lines are a trap: interpolating a Regexp object (not a string) embeds it as (?-mix:cat) with its own flags, so the outer i is ignored and "Cat" does not match. Pass the flag to the inner regex, or interpolate re.source.

6Flags: m, i and x

By default . does not match a newline. Ruby's m flag makes it match one, which is what Python calls re.DOTALL and JavaScript calls s; the name is confusing because Ruby's ^ and $ are line-based already (section 4). i ignores case, and x ignores spaces and newlines in the pattern and allows # comments, so long patterns can be laid out and explained. Flags combine (/re/mi), and Regexp.new takes them as Regexp::IGNORECASE, Regexp::MULTILINE and Regexp::EXTENDED.

flags.rb
html = "<p>one\ntwo</p> <p>three</p>"

# . stops at a newline unless you add m
p html.scan(/<p>(.*?)<\/p>/)
p html.scan(/<p>(.*?)<\/p>/m)

# i ignores case
p "Ruby RUBY ruby".scan(/ruby/i)

# x ignores spaces and allows # comments in the pattern
phone = /
  \(?(\d{3})\)?  # area code, parentheses optional
  [\s.-]?        # separator
  (\d{3})        # exchange
  [.-]?
  (\d{4})        # line number
/x
p "Call (555) 123-4567 or 555.987.6543".scan(phone)

# Flags combine; Regexp.new takes them as constants
p(/a.c/mi)
re = Regexp.new("a.c", Regexp::IGNORECASE | Regexp::MULTILINE)
p re
p "A\nC".match?(re)

Output

Without m, the first paragraph is skipped because .*? cannot cross the newline, and only [["three"]] comes back; with m both paragraphs are found. The x pattern reads like a commented list and finds both phone numbers; inside it, a literal space or # has to be escaped or written as \s. To guard against a pattern that runs for too long on hostile input, Ruby 3.2 added Regexp.timeout = 1.0 (for every regex) and Regexp.new(str, timeout: 1.0); a match that runs over raises Regexp::TimeoutError, a subclass of RegexpError.

7Which should you use?

MethodReturnsBest for
str.scan(re)Array of strings or of group arraysEvery match: most cases
str.to_enum(:scan, re).map { Regexp.last_match }Array of MatchDataEvery match with positions or group names
str.match?(re)true / falseA yes or no, fastest
str.match(re)MatchData or nilThe first match and its groups
str[re] / str[re, 1]String or nilThe first match's text or one group
re =~ strIndex or nilPosition, or named groups as locals
/^…$/ for validationMatches any lineAvoid: use \A and \z

Frequently asked questions

What is the Ruby version of Python's re.findall or JavaScript's matchAll?

str.scan(re) is re.findall: it returns every matched string, or arrays of groups when the pattern has groups. For matchAll or re.finditer, which give match objects with positions, use str.to_enum(:scan, re).map { Regexp.last_match }.

Why does scan return arrays inside an array?

Because the pattern has capture groups: scan then returns only the groups of each match. "cat bat".scan(/(c|b)at/) gives [["c"], ["b"]]. Use a non-capturing group (?:c|b)at or a character class [cb]at to get ["cat", "bat"].

How do I count the regex matches in a string?

Use str.scan(re).size, which is 0 when nothing matches because scan returns an empty array. To count single characters, String#count is simpler: "Hello World".count("o") is 2.

Does scan find overlapping matches?

No, each search starts after the previous match, so "aaaa".scan(/aa/) returns ["aa", "aa"]. To find overlapping matches, put the pattern in a lookahead group: "aaaa".scan(/(?=(aa))/).flatten returns ["aa", "aa", "aa"].

How do I replace all regex matches?

Use gsub; sub replaces only the first. "a1b22c333".gsub(/\d+/, "#") returns "a#b#c#", and sub returns "a#b22c333". With a block, gsub computes each replacement from the match: gsub(/\d+/) { |d| d.size.to_s } gives "a1b2c3". Add ! to change the string in place.

What is the difference between match and =~ in Ruby?

match returns a MatchData object (or nil) that holds the groups and positions. =~ returns the index where the first match starts (or nil) and sets $~, $1 and friends. Use match? when you only need true or false: it is faster and sets no globals. !~ is the negated form of =~ and returns true or false.

Run it yourself

Open any of these in the full Ruby editor to tweak, run and share.

Ruby playground