Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 134 · Standard Library

Regular Expressions

A complete guide to Ruby regular expressions. Learn match, =~, captures, named groups, scan, gsub with blocks, anchors, lookarounds, flags and common pitfalls.

A regular expression (regex) is a small pattern language for describing text. Instead of asking "is this string exactly 2026-10-24?", you ask "does this string contain four digits, a dash, two digits, a dash and two digits?". Regexes are how Ruby programs validate input, pull values out of log lines, split messy text and rewrite it in bulk.

Ruby has regular expressions built into the language. A pattern between slashes, like /\d+/, is a Regexp object, and strings, symbols and case expressions all know how to work with it. This lesson takes you from the first match to captures, named groups, scan, gsub with blocks, lookarounds and the mistakes that cause real bugs. It builds on String Methods, and the next lesson, Text Processing, puts regexes to work on whole documents.

Matching: is the pattern there?

The simplest question is "does this string match?". Ruby gives you several spellings, and they differ in what they return.

Ruby Four ways to ask a question

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

  • match? returns true or false and does nothing else. It is the fastest, because it does not build any match data. Use it whenever you only need a yes or no.
  • =~ returns the index where the match starts, or nil. Index 0 is truthy in Ruby, so if text =~ /x/ works as you expect.
  • match returns a MatchData object, or nil when nothing matches.
  • string[regex] returns the matched text, or nil. The two-argument form slice(regex, 1) returns capture group 1.

The basic building blocks

Pattern Matches
. any character except a newline
\d \w \s a digit, a word character (letter, digit, underscore), whitespace
\D \W \S the opposites
[abc] [a-z] [^0-9] a character from a set, a range, or anything but the set
* + ? zero or more, one or more, zero or one
{2,4} {2,} exactly 3, between 2 and 4, at least 2
a|b a or b
( ) a group, which also captures
\A \z the start and the very end of the string
^ $ the start and end of any line
\b a word boundary
Ruby Building blocks in action

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The anchors matter more than beginners expect. Without \A and \z, a validation pattern accepts any string that merely contains a valid piece. The pattern /\d{4}-\d{2}-\d{2}/ happily matches inside x2026-10-24y. Use the anchors whenever you mean "the whole string looks like this".

Captures and MatchData

Parentheses create groups. Each group remembers the text it matched. After a successful match you can read the groups from the MatchData object.

Ruby Reading captures from MatchData

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

m[0] is the whole match and m[1], m[2], ... are the groups in the order of their opening parentheses. pre_match and post_match are the text before and after the match, both empty here because the pattern covers the whole string. begin and end give the character positions of a group. Ruby also keeps the result of the last match in the special variables $~ (the MatchData), $1, $2, ... Those variables are convenient in quick scripts, but they are per-method and easy to overwrite, so prefer a local m = ...match(...) in real code.

Named captures

Numbers are fragile: add a group and every later index shifts. Named groups use (?<name>...). With match you read them by name. With =~ and a regex literal on the left, Ruby even creates local variables for you.

Ruby Named groups

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The local-variable trick works only when the regex literal is on the left of =~ and has no interpolation. If the pattern is in a variable, use match and read the names from the result. A named group and a numbered group should not be mixed in one pattern, because once you name any group, plain ( ) groups stop capturing.

scan: find every match

match stops at the first hit. scan returns all hits. With no groups you get an array of strings, with groups you get an array of arrays, and with a block it yields each hit.

Ruby scan collects every match

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The (?:...) in the price pattern is a non-capturing group: it groups for the ? quantifier without making a capture, so scan returns only the number.

Substituting: sub and gsub

sub replaces the first match and gsub replaces all of them. The replacement can be a string, a hash or a block.

Ruby sub and gsub in three flavors

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Inside a replacement string, \1 and \2 insert groups and \k<name> inserts a named group. Use single quotes for those strings, as in the example: in double quotes Ruby would consume the backslash first. A block is more flexible: it receives each matched string and returns the replacement, so you can run any Ruby code. The bang version gsub! changes the string in place and returns nil when nothing changed, a classic source of NoMethodError when chained.

Greedy versus lazy

Quantifiers are greedy by default: they grab as much as they can and then back off. Adding ? makes them lazy, matching as little as possible.

Ruby Greedy and lazy quantifiers

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The greedy .+ runs to the end of the string and then backs off only until a > fits, so it swallows everything from the first < to the last >. The lazy .+? stops at the first >. A tighter pattern such as [^>]+ says "anything but a closing bracket" and is often both faster and clearer than a lazy dot.

Lookarounds

A lookaround checks what comes before or after a position without consuming it. It lets you say "digits, but only if followed by px" and get just the digits back.

Ruby Lookahead and lookbehind

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

(?=...) is a positive lookahead, (?!...) a negative lookahead, (?<=...) a positive lookbehind and (?<!...) a negative lookbehind. The last line is a well-known idiom: insert a comma at every position that has a digit before it and a multiple of three digits after it, up to the end of the string.

Flags

Flags change how a pattern behaves. They go after the closing slash.

Flag Effect
i ignore case
m make . match newlines (Ruby's "dotall"; unrelated to ^/$)
x extended: ignore whitespace and allow # comments inside the pattern
o interpolate #{} only once (rarely needed)
Ruby Flags and the extended style

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

In Ruby, ^ and $ always mean the start and end of a line, not of the string. That is why "one\ntwo".scan(/^\w+$/) finds two words, and it is a famous security trap: a check like /^admin$/ accepts "guest\nadmin". Use \A and \z for whole-string checks. The x flag lets you lay out a long pattern with spaces and comments, which is the best way to keep complicated patterns readable.

Building patterns from variables

When user text goes into a pattern, escape it, or characters like . and + will be treated as regex syntax. Regexp.escape does the escaping, and Regexp.union joins several alternatives safely.

Ruby escape and union

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The unescaped pattern 3.5+ means "3, any character, then one or more 5s", so it matches both 3.5 and 3x5 but never the literal 3.5+ you were after. The escaped version finds exactly 3.5+. Always escape user data. Regexp.union also accepts a mix of strings (escaped for you) and regexes, which is why the last line shows a\.b next to (?i-mx:c|d): the second form is how Ruby keeps the i flag local to its own part. If the whole pattern is fixed, put the literal in a constant so Ruby compiles it once.

When patterns go wrong

A match that finds nothing returns nil, and nil has no []. This is the number one regex bug in Ruby programs.

Ruby Using the result of a failed match (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first call prints "42". The second raises NoMethodError: undefined method '[]' for nil. Fix it with the safe-navigation operator, an explicit check, or by letting String#[] do the work, which returns nil quietly:

Ruby Handling the no-match case

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

An invalid pattern raises RegexpError when the Regexp is built. For a literal in your source file that means a SyntaxError at load time, so you only meet RegexpError when the pattern is built from a string at run time.

Catastrophic backtracking

Some patterns can take exponential time on certain inputs, because the engine tries many ways to split the text. Nested quantifiers like (a+)+b are the classic example. Ruby 3.2 and later have a memoizing matcher that protects most patterns, and you can set a time limit as a safety net. Patterns that use a backreference such as \1 cannot be memoized, so they are the ones that still need the limit.

Ruby Setting a regex timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Regexp.linear_time? tells you whether Ruby can match a pattern in time proportional to the text length. The first pattern can, thanks to memoization, while the backreference one cannot, and the risky pattern gives up after 0.2 seconds with Regexp::TimeoutError instead of hanging your program.

When a pattern runs against untrusted text, set Regexp.timeout globally (for example once at startup) and avoid nested quantifiers. Simpler is safer: anchor patterns, prefer character classes such as [^"]* to .*?, and keep alternations non-overlapping.

Regexes in case and elsewhere

A regex is also a valid when branch, because Regexp#=== tests for a match. Many core methods accept regexes too.

Ruby Regexes with case, split, start_with? and more

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

[[:alpha:]] is a POSIX bracket class that understands Unicode letters, so héllo counts as a word. Plain \w in Ruby matches only ASCII letters, digits and underscore unless the string is Unicode and you use \p{Alpha} or the POSIX classes.

Habits of careful regex users

  • Use match? when you only need true or false.
  • Anchor validations with \A and \z, never ^ and $.
  • Name your groups once a pattern has more than two captures.
  • Write long patterns with the x flag and comments.
  • Escape any user-provided text with Regexp.escape.
  • Do not parse nested formats (HTML, JSON, programming languages) with regexes; use a real parser such as the JSON library.
  • Test with awkward input: empty strings, newlines, Unicode, very long strings.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Which method is fastest when you only need to know whether a pattern matches?

    match? returns only true or false and does not create MatchData or set $~, so it does the least work.
  2. 2. What does /^admin$/ accept that /\Aadmin\z/ does not?

    In Ruby ^ and $ match at line boundaries, so a later line that is exactly admin satisfies the pattern. \A and \z anchor to the whole string.
  3. 3. What does "a1b22".scan(/(\w)(\d+)/) return?

    With capture groups, scan returns an array of arrays, one inner array of captures per match.
  4. 4. Why does "abc".match(/x/)[0] raise an error?

    A failed match returns nil. Use String#[] with a regex, safe navigation, or check the result first.
  5. 5. What is the effect of the m flag in a Ruby regex?

    In Ruby, /m means dotall: . matches a newline too. Case-insensitivity is i, and ^/$ always work per line.

Summary

  • A regex literal /.../ is a Regexp; use match? for yes/no, match for MatchData, =~ for the position, str[re] for the matched text.
  • Parentheses capture; (?<name>...) names a capture; (?:...) groups without capturing.
  • scan finds all matches; sub/gsub replace with a string, a hash or a block.
  • \A/\z anchor the whole string; ^/$ anchor lines and cause security bugs in validations.
  • Quantifiers are greedy; add ? for lazy, or use a negated character class.
  • Lookarounds test context without consuming it.
  • Flags: i, m (dotall), x (readable patterns).
  • Escape user text with Regexp.escape, handle the nil from a failed match, and set Regexp.timeout for untrusted input.

Next: Text Processing