TExcelTAD
Home › Ruby › Ruby Regular Expressions

Ruby Regular Expressions

A regular expression (regex) is a pattern that describes text: "three digits", "a word followed by @", "anything in brackets". Ruby has regexes built into the language with the /.../ literal syntax, and string methods such as match?, scan, sub and gsub accept them everywhere.

Testing for a match

ruby · try it yourself
p "order-2381".match?(/\d+/)
p "hello" =~ /ll/
p "hello" =~ /z/
p /ruby/i.match?("I love RUBY")
p "2025-07-14".match?(/\A\d{4}-\d{2}-\d{2}\z/)
true
2
nil
true
true
  • match? returns true/false — the fastest check.
  • =~ returns the index of the match, or nil.
  • The i flag after the closing slash makes the match case-insensitive.
  • \A and \z anchor the pattern to the start and end of the whole string.

Pattern building blocks

Pattern Matches
. any character except newline
\d / \D a digit / a non-digit
\w / \W word character [a-zA-Z0-9_] / non-word
\s / \S whitespace / non-whitespace
[abc], [a-z], [^0-9] one of / range / none of
* + ? 0 or more, 1 or more, 0 or 1
{3}, {2,4} exactly 3, between 2 and 4
^ $ start / end of a line
\A \z start / end of the string
\b word boundary
(...) capture group
(?<name>...) named capture group
a|b a or b

Note: In Ruby, ^ and $ match at every line break. To validate an entire input, use \A and \z — otherwise "ok\n<script>" could sneak past /^ok$/.

Capturing parts of a match

match returns a MatchData object (or nil). Groups in parentheses are available by number or name:

ruby · try it yourself
m = "Invoice INV-2025-0042 total 99.50".match(/INV-(\d{4})-(\d+)/)
p m[0]
p m[1]
p m[2].to_i

date = "Due: 2025-11-30".match(/(?<year>\d{4})-(?<month>\d\d)-(?<day>\d\d)/)
p date[:year]
p date[:month].to_i
p date.named_captures
"INV-2025-0042"
"2025"
42
"2025"
11
{"year" => "2025", "month" => "11", "day" => "30"}

A shortcut: string[regex, group] returns just one captured piece:

ruby · try it yourself
p "user=amira;role=admin"[/role=(\w+)/, 1]
p "no match here"[/\d+/]
"admin"
nil

Finding all matches with scan

ruby · try it yourself
text = "Call 555-0101 or 555-0199, not 12-34."
p text.scan(/\d{3}-\d{4}/)

tags = "Loving #ruby and #regex today! #learning"
p tags.scan(/#(\w+)/).flatten

pairs = "a=1, b=22, c=333"
p pairs.scan(/(\w)=(\d+)/).to_h { |k, v| [k.to_sym, v.to_i] }
["555-0101", "555-0199"]
["ruby", "regex", "learning"]
{a: 1, b: 22, c: 333}

With groups, scan returns an array of arrays — one inner array per match.

Replacing with sub and gsub

ruby · try it yourself
p "2025-07-14".sub(/(\d+)-(\d+)-(\d+)/, '\3/\2/\1')
p "too    many   spaces".gsub(/\s+/, " ")
p "card 4111 1111 1111 1234".gsub(/\d(?=(?:\s?\d){4})/, "*")
p "hello world".gsub(/\b\w/) { |c| c.upcase }
p "cost: 10 EUR, 25 EUR".gsub(/(\d+) EUR/) { "#{($1.to_i * 1.1).round} USD" }
p "snake_case_name".gsub(/_(\w)/) { $1.upcase }
"14/07/2025"
"too many spaces"
"card **** **** **** 1234"
"Hello World"
"cost: 11 USD, 28 USD"
"snakeCaseName"
  • In a replacement string, \1, \2 refer to groups (use single quotes so the backslashes survive).
  • With a block, the block's return value replaces each match; $1, $2 hold the groups.
  • (?=...) is a lookahead: it checks what follows without consuming it.

Splitting with a regex

ruby · try it yourself
p "one, two;three  four".split(/[,;\s]+/)
p "CamelCaseString".split(/(?=[A-Z])/)
["one", "two", "three", "four"]
["Camel", "Case", "String"]

Validating input

ruby · try it yourself
EMAIL = /\A[\w+.-]+@[\w-]+(\.[\w-]+)+\z/
POSTCODE = /\A\d{5}\z/

def check(label, value, pattern)
  status = value.match?(pattern) ? "valid" : "invalid"
  puts "#{label.ljust(9)} #{value.inspect.ljust(22)} #{status}"
end

check("email", "zoe.k+news@mail.co.uk", EMAIL)
check("email", "zoe@localhost", EMAIL)
check("postcode", "10115", POSTCODE)
check("postcode", "1011", POSTCODE)
email     "zoe.k+news@mail.co.uk" valid
email     "zoe@localhost"        invalid
postcode  "10115"                valid
postcode  "1011"                 invalid

Flags and the x mode

Flag Effect
i ignore case
m . also matches newlines
x extended: ignore spaces, allow # comments in the pattern
ruby · try it yourself
PHONE = /
  \A
  \+?(\d{1,3})?   # optional country code
  [\s-]?
  (\d{3})         # area
  [\s-]?
  (\d{4})         # number
  \z
/x

p "+44 207 1234".match(PHONE)&.captures
p "207-1234".match(PHONE)&.captures
p "abc".match(PHONE)&.captures
["44", "207", "1234"]
[nil, "207", "1234"]
nil

Tip: Try patterns interactively in the Regex course playground on this site, or at rubular.com, before putting them in your code.

Test yourself

What does "abc123def45".scan(/\d+/) return?

  1. ["123"]
  2. ["123", "45"]
  3. [1, 2, 3, 4, 5]
  4. "12345"

Which anchors match the start and end of the whole string in Ruby?

  1. ^ and $
  2. \A and \z
  3. \b and \B
  4. < and >

What does "x-1"[/(\w)-(\d)/, 2] return?

  1. "x"
  2. "1"
  3. "x-1"
  4. nil