↑
Main Page
Lookaheads
Lookaheads
Sometimes you may want to capture a particular group of characters only if they appear before another
set of characters. Using lookaheads makes this process easy.
A
lookahead
is just what it sounds like: It tells the regular expression evaluator to look ahead any number
of characters without losing its spot. There are both positive and negative lookaheads. Positive lookaheads
check whether a certain set of characters comes next. Negative lookaheads determine if a certain set of
characters does not come next.
A positive lookahead is created by enclosing a pattern between
(?=
and
)
. Note that this is not a group,
even though it uses parentheses. In fact, groups don’t recognize that lookaheads (either positive or nega-
tive) exist. Consider the following:
var sToMatch1 = “bedroom”;
var sToMatch2 = “bedding”;
var reBed = /(bed(?=room))/;
alert(reBed.test(sToMatch1)); //outputs “true”
alert(RegExp.$1); //outputs “bed”
alert(reBed.test(sToMatch2)); //outputs “false”
In this example,
reBed
matches
“bed”
only if it is followed by
“room”
. Therefore, it matches
sToMatch1
but not
sToMatch2
. After testing the expression against
sToMatch1
, this code outputs the
contents of
RegExp.$1
, which is
“bed”
, not
“bedroom”
. The
“room”
part of the pattern is contained
inside of a lookahead and so isn’t returned as part of the group.
At the other end of the spectrum is a negative lookahead, created by enclosing a pattern between
(?!
and
)
. The previous example can be changed to use a negative lookahead to match
“bedding”
instead
of
“bedroom”
:
var sToMatch1 = “bedroom”;
var sToMatch2 = “bedding”;
var reBed = /(bed(?!room))/;
alert(reBed.test(sToMatch1)); //outputs “false”
alert(reBed.test(sToMatch2)); //outputs “true”
alert(RegExp.$1); //outputs “bed”
Here, the expression is changed to match
“bed”
only if
“room”
doesn’t follow it, so the pattern matches
“bedding”
but not
“bedroom”
. After testing against
sToMatch2
,
RegExp.$1
contains
“bed”
once
again, not
“bedding”
.
Boundaries
Boundaries
are used in regular expressions to indicate the location of a pattern. The following table lists
the available boundaries:
Although JavaScript supports regular-expression lookaheads, it does not support
lookbehinds, which match patterns such as
“match b only if it isn’t pre-
ceded by a”
.
210
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 210
Free JavaScript Editor
Ajax Editor
©
→