Solution – java.util.regex.PatternSyntaxException: Unclosed character class near index 0

The java.util.regex.PatternSyntaxException: Unclosed character class near index 0 example shows the reasons for this exception. It also shows how to fix it using various solutions.

What is java.util.regex.PatternSyntaxException: Unclosed character class near index and what causes it?

The opening square bracket character “[” is a meta-character in the regular expression, which means it has a special meaning. It is used to specify the character class. If we specify the opening square bracket in the regex pattern to match it literally without escaping it, it causes this exception.

Reason 1: Trying to split a string by square bracket using the split method?

This exception will be thrown when you try to split the string by an opening square bracket using the split method. Since the split method accepts a regex pattern and the opening square bracket is a meta-character in regex,  Java throws this exception as given below.

Output

Solution:

We need to escape the “[” character in the split method.

Output

You can also use the quote method of the Pattern class instead of escaping the pattern as given below.

Reason 2: Trying to replace square brackets using the replaceAll method?

Just like the split method, the replaceAll method also accepts the regex pattern.

Output

Solution:

We need to escape all meta-characters we need to match literally in the replaceAll method.

Output

Reason 3: Trying to mention the character class in the regex pattern?

You are trying to specify the character range to match but forgot to close the square bracket as given below. Like in the example given below, the pattern “[0-9” is missing the closing square bracket for the numeric character class.

Output

Solution:

Make sure that you have a closing square bracket for every character class specified.

Output

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 *