Java RegEx Positive and Negative Lookahead

Java Regex – positive and negative lookahead example shows how to write regular expression patterns to perform positive lookahead and negative lookahead in Java.

What is a lookahead regular expression?

Let’s first understand what is a lookahead expression. Let’s say you have a string “CatBirdCatDog” and you want to extract the string “Cat” which is followed by the string “Dog”. In a normal regular expression, I will write something like the code given below.

Output

As you can see from the output, we found the match but the regular expression also captured the string “Dog”. So instead of output “Cat”, we got output as “CatDog”.

This is where the lookahead regular expression is useful. The lookahead expression matches the subsequence to the right of the current position but does not include it in the match. As the name “lookahead” suggests, it just looks ahead to check the specified condition, it does not include the condition in the final match.

How to write positive lookahead regular expression in Java?

The positive lookahead expression is used when we want to find something that is followed by something else but we do not want that something else to be included in the match. For example, we want to match “X” that is followed by a “Y”, but we do not want “Y” to be included in the match, we just want to check.

Syntax of positive lookahead expression is as given below.

Example:

Output

As we can see from the output, this time the output only includes “Cat” not “CatDog”.

How to write negative lookahead regular expression in Java?

The negative lookahead expression is exactly the opposite of the positive lookahead expression. It is used when we want to find something that is not followed by something else.¬†For example, we want to match “X” that is not followed by a “Y”.

Syntax of negative lookahead expression is as given below.

Example:

Output

As we can see from the output, the regular expression found the string “Cat” that is not followed by the string “Dog”.

This example is a part of the Java Regular Expression Tutorial with Examples.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *