You want to emulate a NEAR search using a regular
expression. For readers unfamiliar with the term, some search tools that
use Boolean operators such as NOT and OR also have a special operator
called NEAR. Searching for “word1 NEAR word2” finds word1
and word2
in any order, as long
as they occur within a certain distance of each other.
If you’re searching for just two different words, you can combine
two regular expressions—one that
matches word1
before word2
,
and another that flips the order of the words. The following regex
allows up to five words to separate the two you’re searching for:
(?:word1W+(?:w+W+){0,5}?word2|word2W+(?:w+W+){0,5}?word1)
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
(?: word1 # first term W+ (?:w+W+){0,5}? # up to five words word2 # second term | # or, the same pattern in reverse: word2 # second term W+ (?:w+W+){0,5}? # up to five words word1 # first term )
Regex options: Free-spacing, case insensitive |
Regex flavors: .NET, Java, XRegExp, PCRE, Perl, Python, Ruby |
The second regular expression here uses the free-spacing option and adds whitespace and comments for readability. Apart from that, the two regular expressions are identical. JavaScript doesn’t support free-spacing mode unless you use the XRegExp library, but the other listed regex flavors allow you to take your pick. Recipes 3.5 and 3.7 show examples of how you can add these regular expressions to your search form or other code.
This regular expression puts two inverted copies of the same
pattern back to back, and then surrounds them with word boundaries. The
first subpattern matches word1
, followed by between zero and five
words, and then word2
. The second subpattern matches the
same thing, with the order of word1
and word2
reversed.
The lazy quantifier ‹{0,5}?
› appears in both of the subpatterns. It
causes the regular expression to match as few words as possible between
the two terms you’re searching for. If you run the regular expression
over the subject text word1 word2 word2
, it will match
word1 word2
because that has fewer words (zero) between the start and end points. To
configure the distance permitted between the target words, change the 0
and 5 within the two quantifiers to your preferred values. For example,
if you changed them to ‹{1,15}?
›, that would allow up to 15 words between
the two you’re looking for, and require that they be separated by at
least one other word.
The shorthand character classes that are used to match word
characters and nonword characters (‹w
› and
‹W
›,
respectively) follow the quirky regular expression definition of which
characters words are composed of (letters, numbers, and
underscore).
Often, there are many ways to write the same regular expression. In this book, we’ve tried hard to balance the trade-offs between portability, brevity, efficiency, and other considerations. However, sometimes solutions that are less than ideal can still be educational. The next two regular expressions illustrate alternative approaches to finding words near each other. We don’t recommend actually using them, because although they match the same text, they will typically take a little longer to do so. They also work with fewer regular expression flavors.
This first regular expression uses a conditional (see Recipe 2.17) to determine whether to match
word1
or
word2
at the
end of the regex, rather than simply stringing reversed patterns
together. The conditional checks if capturing group 1 participated in
the match, which would mean that the match started with word2
:
(?:word1|(word2))W+(?:w+W+){0,5}?(?(1)word1|word2)
Regex options: None |
Regex flavors: .NET, PCRE, Perl, Python |
This next version once again uses a conditional to determine which word should be matched at the end, but it adds two more regular expression features into the mix:
(?:(?<w1>word1)|(?<w2>word2))W+(?:w+W+){0,5}?(?(w2)(?&w1)|(?&w2))
Regex options: None |
Regex flavors: PCRE 7, Perl 5.10 |
Here, named capturing groups, written as ‹(?<
›, surround the first
instances of ‹name
>⋯)word1
› and
‹word2
›. This allows you
to use the ‹(?&
›
subroutine syntax to reuse a subpattern that is
called by name. This does not work the same as a backreference to a
named group. A named backreference, such as ‹name
)k<
›
(.NET, Java 7, XRegExp, PCRE 7, Perl 5.10) or ‹name
>(?P=
› (PCRE 4,
Perl 5.10, Python) lets you rematch text that has already been matched
by a named capturing group. A subroutine such as ‹name
)(?&
› allows
you to reuse the actual pattern contained within the corresponding
group. You can’t use a backreference here, because that would only
allow rematching words that have already been matched. The subroutines
within the conditional at the end of the regex match the word from the
two provided options that hasn’t already been
matched, without having to spell out the words again. This means there
is only one place in the regex to update if you need to reuse it to
match different words.name
)
Ruby 1.9 supports named subroutines using the syntax ‹g<
›,
but since Ruby 1.9 doesn’t support conditionals, it can’t run the
regexes shown earlier. PCRE 4 was the first regex library to support
named subroutines, but back then it used the syntax ‹name
>(?P>
›,
which is now discouraged in favor of the Perl-compatible ‹name
)(?&
› that
was added in Perl 5.10 and PCRE 7. PCRE 7.7 added Ruby 1.9’s
subroutine syntax as yet another supported alternative.name
)
Matching two words near each other is a fairly straightforward task. After all, there are only two possible ways to order them. But what if you want to match three words in any order? Now there are six possible orders (see Example 5-1). The number of ways you can shift a given set of words around is n!, or the product of consecutive integers 1 through n (“n factorial”). With four words, there are 24 possible ways to order them. By the time you get to 10 words, the number of arrangements explodes into the millions. It is simply not viable to match more than a few words near each other using the regular expression techniques discussed so far.
One way to solve this problem is by repeating a group that matches the required words or any other word (after a required word has been matched), and then using conditionals to prevent a match attempt from finishing successfully until all of the required words have been matched. Following is an example of matching three words in any order with up to five other words separating them:
(?:(?>(word1)|(word2)|(word3)|(?(1)|(?(2)|(?(3)|(?!))))w+)W*?){3,8}↵ (?(1)(?(2)(?(3)|(?!))|(?!))|(?!))
Regex options: Case insensitive |
Regex flavors: .NET, PCRE, Perl |
Example 5-1. Many ways to arrange a set
Two values: [ 12, 21 ] = 2 possible arrangements Three values: [ 123, 132, 213, 231, 312, 321 ] = 6 possible arrangements Four values: [ 1234, 1243, 1324, 1342, 1423, 1432, 2134, 2143, 2314, 2341, 2413, 2432, 3124, 3142, 3214, 3241, 3412, 3421, 4123, 4132, 4213, 4231, 4312, 4321 ] = 24 possible arrangements Factorials: 2! = 2 × 1 = 2 3! = 3 × 2 × 1 = 6 4! = 4 × 3 × 2 × 1 = 24 5! = 5 × 4 × 3 × 2 × 1 = 120 ⋮ 10! = 10 × 9 × 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1 = 3628800
Here again is the regex, except that the atomic group (see Recipe 2.14) has been replaced by a standard, noncapturing group. This adds support for Python at the cost of some efficiency:
(?:(?:(word1)|(word2)|(word3)|(?(1)|(?(2)|(?(3)|(?!))))w+)W*?){3,8}↵ (?(1)(?(2)(?(3)|(?!))|(?!))|(?!))
Regex options: Case insensitive |
Regex flavors: .NET, PCRE, Perl, Python |
The ‹{3,8}
›
quantifiers in the regular expressions just shown account for the
three required words, and thus allow zero to five words in between
them. The empty negative lookaheads, which look like ‹(?!)
›,
will never match and are therefore used to block certain paths
through the regex until one or more of the required words have been
matched. The logic that controls these paths is implemented using
two sets of nested conditionals. The first set prevents matching any
old word using ‹w+
›
until at least one of the required words have been matched. The
second set of conditionals at the end forces the regex engine to
backtrack or fail unless all of the required words have been
matched.
That’s the brief overview of how this works, but rather than getting further into the weeds and describing how to add additional required words, let’s take a look at an improved implementation that adds support for more regex flavors, and involves a bit of a trick.
The ugly solution works, but it could probably win a regex obfuscation contest for being so difficult to read and manage. It would only get worse if you added more required words into the mix.
Fortunately, there’s a regular expression hack you can use that makes this a lot easier to follow, while also adding support for Java and Ruby (neither of which supports conditionals).
The behavior described in this section should be used with caution in production applications. We’re pushing expectations for regex behavior into places that are undocumented for most regex libraries.
(?:(?>word1()|word2()|word3()|(?>1|2|3)w+)W*?){3,8}123
Regex options: Case insensitive |
Regex flavors: .NET, Java, PCRE, Perl, Ruby |
(?:(?:word1()|word2()|word3()|(?:1|2|3)w+)W*?){3,8}123
Regex options: Case insensitive |
Regex flavors: .NET, Java, PCRE, Perl, Python, Ruby |
Using this construct, it’s easy to add more required words. Here’s an example that allows four required words to appear in any order, with a total of up to five other words between them:
(?:(?>word1()|word2()|word3()|word4()|↵ (?>1|2|3|4)w+)W*?){4,9}1234
Regex options: Case insensitive |
Regex flavors: .NET, Java, PCRE, Perl, Ruby |
(?:(?:word1()|word2()|word3()|word4()|↵ (?:1|2|3|4)w+)W*?){4,9}1234
Regex options: Case insensitive |
Regex flavors: .NET, Java, PCRE, Perl, Python, Ruby |
These regular expressions intentionally use empty
capturing groups after each of the required words. Since any attempt
to match a backreference such as ‹1
› will fail if the corresponding capturing
group has not yet participated in the match, backreferences to empty
groups can be used to control the path a regex engine takes through
a pattern, much like the more verbose conditionals we showed
earlier. If the corresponding group has already participated in the
match attempt when the engine reaches the backreference, it will
simply match the empty string and move on.
Here, the ‹(?>1|2|3)
› grouping prevents matching a
word using ‹w+
› until
at least one of the required words has been matched. The
backreferences are repeated at the end of the pattern to prevent any
match from successfully completing until all of the required words
have been found.
Python does not support atomic groups, so once again the examples that list Python among the regex flavors replace such groups with standard noncapturing groups. Although this makes the regexes less efficient, it doesn’t change what they match. The outermost grouping cannot be atomic in any flavor, because in order for this to work, the regex engine must be able to backtrack into the outer group if the backreferences at the end of the pattern fail to match.
Even though JavaScript supports all the syntax used in the Python versions of this pattern, it has two behavioral rules that prevent this trick from working like the other flavors. The first issue is what is matched by backreferences to capturing groups that have not yet participated in a match. The JavaScript specification dictates that such backreferences match the empty string, or in other words, they always match successfully. In just about every other regular expression flavor, the opposite is true: they never match, and as a result they force the regex engine to backtrack until either the entire match fails or the group they reference participates, thereby providing the possibility that the backreference too will match.
The second difference with the JavaScript flavor involves the
value remembered by capturing groups nested within a repeated, outer
group—for example, ‹((a)|(b))+
›. With most regex flavors, the
value remembered by a capturing group within a repeated grouping is
whatever the group matched the last time it participated in the
match. So, after ‹(?:(a)|(b))+
› is used to match ab
, the value of
backreference 1 would be a
. However, according to the JavaScript
specification, the value of backreferences to nested groups is reset
every time the outer group is repeated. Hence, ‹(?:(a)|(b))+
› would still
match ab
,
but backreference 1 after the match is complete would reference a
nonparticipating capturing group, which in JavaScript would match an
empty string within the regex
itself and be returned as undefined
in, for example, the array
returned by the
method.regexp
.exec()
Either of these behavioral differences found in the JavaScript regex flavor are enough to prevent emulating conditionals using empty capturing groups, as described here.
If you simply want to test whether a list of words can be found anywhere in a subject string without regard for their proximity, positive lookahead provides a way to do so using one search operation.
In many cases it’s simpler and more efficient to perform discrete searches for each term you’re looking for, while keeping track of whether all tests come back positive.
^(?=.*?word1)(?=.*?word2).*
Regex options: Case insensitive, dot matches line breaks (“^ and $ match at line breaks” must not be set) |
Regex flavors: .NET, Java, XRegExp, PCRE, Perl, Python, Ruby |
^(?=[sS]*?word1)(?=[sS]*?word2)[sS]*
Regex options: Case insensitive (“^ and $ match at line breaks” must not be set) |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
These regular expressions match the entire string they’re run against if all of your target words are found within it; otherwise, they will not find any match. JavaScript programmers cannot use the first version unless using the XRegExp library, because standard JavaScript doesn’t support the “dot matches line breaks” option.
You can implement these regular expressions by following the
code in Recipe 3.6. Simply change
the ‹word1
› and ‹word2
› placeholders to the terms
you’re searching for. If you’re checking for more than two words, you
can add as many lookaheads to the front of the regex as you need. For
example, ‹^(?=.*?word1)(?=.*?word2)(?=.*?word3).*
›
searches for three words.
Recipe 5.5 explains how to find any word not followed by a specific word. Recipe 5.6 explains how to find any word not preceded by 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.8 explains alternation. Recipe 2.9 explains grouping. Recipe 2.10 explains backreferences. Recipe 2.11 explains named capturing groups. Recipe 2.12 explains repetition. Recipe 2.14 explains atomic groups. Recipe 2.17 explains conditionals.