Lookarounds are essentially non-capturing groups used to match patterns based on what they have either behind or in front of an expression. There are four types of lookarounds, and they are going to be listed below.

Positive Lookahead

This is used to match an expression that is followed by some specific term. See the example below:

Regex:

after(?= the)

Matches:

The memo was written immediately after the meeting, a day after Michael Flynn resigned, according to US media.

In this example, the regular expression is looking for the word after that is followed by the word the, without consuming the word the itself.

This feature is very useful on scenarios where we need to match an expression that we don't know what it is, but we know exactly what surrounds it.

Negative Lookahead

This feature is just like the previous one, except that negative lookaheads matches expressions that are NOT followed by a specific term. Check it out:

Regex:

after(?! the)

Matches:

The memo was written immediately after the meeting, a day after Michael Flynn resigned, according to US media.

We used the same example of the previous section. Since now we are negating the expression the, the regex engine matches the after word followed by Michael instead.

Positive Lookbehinds

This is used to match an expression that follows a specific term. See the example below:

Regex:

(?<=be )\w+

Matches:

I used to be brave.
I used to be strong.
I used to be fearless.

In this example, we wanted to capture the word characters after the word be. Simple as that.

Negative Lookbehinds

And again, like the previous feature, this one does the opposite. It matches an expression that doesn't follow an specific term. See the example:

Regex:

(?<!int )value\w

Matches:

int valueA = 3;
int valueB = 5;
double valueC = 2.2;
String valueD = "Something";

This example captures all variable names that start with the word value, followed by a word character, and aren't of int type.