3.1. Regular Expression Syntax

The typical regular expression is delimited by a pair of slashes; the %r form can also be used. Table 3.1, “Basic Regular Expressions,” gives some simple examples:

Table 3.1. Basic Regular Expressions
RegexExplanation
/Ruby/Match the single word Ruby
/[Rr]uby/Match Ruby or ruby
/^abc/Match an abc at beginning of line
%r(xyz$)Match an xyz at end of line
%r|[0-9]*|Match any sequence of (zero or more) digits

It is also possible to place a modifier, consisting of a single letter, immediately after a regex. Table 3.2 shows the most common modifiers:

Table 3.2. Regular Expression Modifiers
ModifierMeaning
iIgnore case in regex
oPerform expression substitution only once
mMultiline mode (dot matches newline)
xExtended regex (allow ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.