Java RegEx NOT Operator

Java regex not operator example shows how to use a not operator in Java regular expression. It also shows how to use a not operator in a character class in regex.

How to use NOT operator inside Java regex?

It may come as a surprise but Java regex does not have a NOT operator like the regex OR operator. However, there are some workarounds using which you do pretty much everything.

1. Using a character class

In Java regex, we can specify the character class with a “^” sign. Inside a character class, it means a NOT operator. For example, the pattern “[^0-9]” matches with any character that is not a digit between 0 to 9.

The below-given example code uses that syntax to remove all non-digit characters from a string using the replaceAll method.

Output

As you can see from the output, the regex pattern replaced every character that is NOT a digit with an empty string, leaving only digits in the string.

2. Using a negative lookahead

The negative lookahead regex expression is used to check if something is not followed by something else. For example, we want to find a digit in a string that is not followed by a space character. The syntax of the negative lookahead is “(?!Expression)”.

The below given example searches a number in the string that is not followed by the word “out”.

Output

The above example uses the regex pattern “(\\d+)\\s(?!out)”. It means one or more digits followed by a space and not followed by the word “out”. That matches with the number “10”. Using this technique you can extract a substring from a string using the NOT operator.

3. Using the negative lookbehind

Just like the negative lookahead, you can also use the negative lookbehind regex expression. It is used when we want to search for something that is not preceded by something else. The syntax for a negative lookbehind is “(?<!Expression)”.

For example, we want to search a number in a string that is not preceded by the start of the string as give in the below example.

Output

The pattern “(?<!^)(\\d+)” means that any digit one or more times that is not preceded by the start of the string. The “^” character outside a character class means the start of the string. Since we do not want to match a number at the start, the only number our pattern matches is “10” which is in the middle of the string.

If you want to learn more about regular expressions, please visit the Java Regex tutorial.

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 *