Look-Arounds


Look-arounds are used to check what comes before or after, without consuming or capturing. ("Without consuming" means that matches for look-around assertions no not become part of the string to be replaced.

Look-around patterns have two components:

  1. The main pattern to match, and
  2. a "test" pattern that will be used to qualify the main pattern's match

The test pattern does not consume or capture any text, it is purely a logical test.

One can think of look-arounds as "conditional patterns". That is, they create patterns that only match if another condition is met.

Look-arounds come in two types:

Positive
Match this pattern if the test pattern also matches
Negative
Match this pattern if the test pattern does not match

While each look-around applies in one of two directions:

Ahead
The test pattern is applied to the right of the main pattern
Behind
The test pattern is applied to the left of the main pattern

We will take a look at each of these in the following sections.