You have several problems in this case:
You want to find all occurrences of both color
and colour
in a
string.
You want to find any of three words that end with “at”:
bat
,
cat
, or
rat
.
You want to find any word ending with phobia
.
You want to find common variations on the name “Steven”:
Steve
,
Steven
,
and Stephen
.
You want to match any common form of the term “regular expression.”
Regular expressions to solve each of the problems just listed are shown in turn. All of these solutions are listed with the case insensitive option.
colou?r
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
[bcr]at
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
w*phobia
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
All five of these regular expressions use word
boundaries (‹›) to
ensure that they match only complete words. The patterns use several
different approaches to allow variation in the words that they
match.
This regular expression will match color
or colour
, but will not match within colorblind
. It uses the
‹?
›
quantifier to make its preceding u
optional. Quantifiers such as
‹?
› do not work like the
wildcards that many people are more familiar with. Instead, they bind
to the immediately preceding element, which can be either a single
token (in this case, the literal character u
) or a group of tokens wrapped in
parentheses. The ‹?
›
quantifier repeats the preceding element zero or one time. The regex
engine first tries to match the element that the quantifier is bound
to, and if that doesn’t work, the engine moves forward without
matching it. Any quantifier that allows zero repetitions effectively
makes the preceding element optional, which is exactly what we want
here.
This regular expression uses a character class to match
b
,
c
, or
r
, followed
by the literal characters at
. You could do the same thing using
‹(?:b|c|r)at
›,
‹(?:bat|cat|rat)
›,
or ‹bat|cat|rat
›. However, any time the
difference between allowed matches is a choice from one of a list of
characters, you’re better off using a character class. Not only do
character classes provide a more compact and readable syntax (thanks
to being able to drop all the vertical bars and use ranges such as
A–Z), most regex engines also provide far superior optimization for
character classes. Alternation using vertical bars requires the engine
to use the computationally expensive backtracking algorithm, whereas
character classes use a simpler search approach.
A few words of caution, though. Character classes are among the most frequently misused regular expression features. It’s possible that they’re not always documented well, or maybe some readers just skimmed over the details. Whatever the reasons, don’t let yourself make the same newbie mistakes. Character classes are only capable of matching one character at a time from the characters specified within them—no exceptions.
Following are two of the most common ways that character classes are misused:
Sure, something like ‹[cat]{3}
› will match cat
, but it will
also match act
, ttt
, and any other three-character
combination of the listed characters. The same applies to
negated character classes such as ‹[^cat]
›, which matches any single
character that is not c
, a
, or t
.
By definition, character classes allow a choice between
the characters specified within them. ‹[a|b|c]
› matches a single character from
the set “abc|”, which is probably not what you want. And even if
it is, the class contains a redundant vertical bar.
See Recipe 2.3 for all the details you need to use character classes correctly and effectively.
This pattern combines features from the two previous regexes to
provide the variation in the strings it matches. Like the “bat, cat,
or rat” regex, it uses a character class (the shorthand ‹w
›) that matches any word
character. It then uses the ‹*
›
quantifier to repeat the shorthand class zero or more times, similar
to the “color or colour” regex’s use of ‹?
›.
This regular expression matches, for example, arachnophobia
and hippopotomonstrosesquipedaliophobia
.
Because the ‹*
› allows
zero repetitions, it also matches phobia
on its own. If you want to require
at least one word character before the “phobia” suffix, change the
‹*
› to ‹+
›.
Here we add alternation to the mix as yet another means for
regex variation. A noncapturing group, written as ‹(?:⋯)
›, limits the reach of the ‹|
› alternation operator. The
‹?
› quantifier used
inside the group’s first alternation option makes the preceding
‹n
› character optional.
This improves efficiency (and brevity) versus the equivalent ‹Ste(?:ve|ven|phen)
›. The
same principle explains why the literal string ‹Ste
› appears at the front of the
regular expression, rather than being repeated three times as with
‹(?:Steve|Steven|Stephen)
› or ‹Steve|Steven|Stephen
›. Some
backtracking regular expression engines are not smart enough to figure
out that any text matched by these latter regexes must start with
Ste
.
Instead, as the engine steps through the subject string looking for a
match, it will first find a word boundary, then check the following
character to see if it is an S
. If
not, the engine must try all alternative paths through the regular
expression before it can move on and start over again at the next
position in the string. Although it’s easy for a human to see that
this would be a waste of effort (since the alternative paths through
the regex all start with Ste
), the
engine doesn’t know this. If instead you write the regex as ‹Ste(?:ven?|phen)
›, the
engine immediately realizes that it cannot match any string that does
not start with those characters.
For an in-depth look under the hood of a backtracking regular expression engine, see Recipe 2.13.
The final example for this recipe mixes alternation, character classes, and quantifiers to match any common variation of the term “regular expression.” Since the regular expression can be a bit difficult to take in at a glance, let’s break it down and examine each of its parts.
This next regex uses the free-spacing option, which is not available in standard JavaScript. Since whitespace is ignored in free-spacing mode, the literal space character has been escaped with a backslash:
# Assert position at a word boundary. reg # Match "reg". (?: # Group but don't capture: ular # Match "ular ". expressions? # Match "expression" or "expressions". | # Or: ex # Match "ex". (?: # Group but don't capture: ps? # Match "p" or "ps". | # Or: e[sn] # Match "es" or "en". )? # End the group and make it optional. ) # End the group. # Assert position at a word boundary.
Regex options: Free-spacing, case insensitive |
Regex flavors: .NET, Java, XRegExp, PCRE, Perl, Python, Ruby |
This pattern matches any of the following seven strings, with any combination of upper- and lowercase letters:
regular
expressions
regular
expression
regexps
regexp
regexes
regexen
regex
Recipe 5.1 explains how to find a specific word. Recipe 5.2 explains how to find any of multiple words. Recipe 5.4 explains how to find all except a specific word.
Techniques used in the regular expressions in this recipe are discussed in Chapter 2. Recipe 2.3 explains character classes. Recipe 2.6 explains word boundaries. Recipe 2.9 explains grouping. Recipe 2.12 explains repetition.