Previous: , Up: pregexp syntax   [Index]


51.3.7 Looking ahead and behind

We can have assertions in our pattern that look ahead or behind to ensure that a subpattern does or does not occur. These “look around” assertions are specified by putting the subpattern checked for in a cluster whose leading characters are:

?=

Positive lookahead.

?!

Negative lookahead.

?<=

Positive lookbehind.

?<!

Negative lookbehind.

Note that the subpattern in the assertion does not generate a match in the final result. It merely allows or disallows the rest of the match.

Lookahead

Positive lookahead (?=) peeks ahead to ensure that its subpattern could match.

(pregexp-match-positions "grey(?=hound)"
  "i left my grey socks at the greyhound")
⇒ ((28 . 32))

The regexp grey(?=hound) matches grey, but only if it is followed by hound. Thus, the first grey in the text string is not matched.

Negative lookahead (?!) peeks ahead to ensure that its subpattern could not possibly match.

(pregexp-match-positions "grey(?!hound)"
  "the gray greyhound ate the grey socks")
⇒ ((27 . 31))

The regexp grey(?!hound) matches grey, but only if it is not followed by hound. Thus the grey just before socks is matched.

Lookbehind

Positive lookbehind (?<=) checks that its subpattern could match immediately to the left of the current position in the text string.

(pregexp-match-positions "(?<=grey)hound"
  "the hound in the picture is not a greyhound")
⇒ ((38 . 43))

The regexp (?<=grey)hound matches hound, but only if it is preceded by grey.

Negative lookbehind (?<!) checks that its subpattern could not possibly match immediately to the left.

(pregexp-match-positions "(?<!grey)hound"
  "the greyhound in the picture is not a hound")
⇒ ((38 . 43))

The regexp (?<!grey)hound matches hound, but only if it is not preceded by grey.

Lookaheads and lookbehinds can be convenient when they are not confusing.


Previous: , Up: pregexp syntax   [Index]