Java RegEx – How to Escape and Match Bracket

Java RegEx – How to Escape and Match bracket example shows how to escape and match square bracket and round bracket (parentheses) literally in Java regular expression pattern.

How to match a square bracket using regex in Java?

The square brackets in Java’s regular expression have a special meaning. They are used to define a character class. See the below-given regex pattern for example.

This pattern matches with any character that is not a digit between 0 to 9.

Output

As you can see from the output, all the non-digit characters were removed from the string.

Since the square brackets are used to define a character class in a regex, we cannot directly mention that when we want to match it literally. See the below example.

Output

As you can see from the output, the code throws java.util.regex.PatternSyntaxException: Unclosed character class near index exception, since it was expecting a character class when it encountered the opening square bracket.

In order to match the square bracket literally, we need to escape it like “\\[” as given below.

Output

How to match a round bracket or parentheses using regex in Java?

Just like the square bracket, a round bracket has also a special meaning in the regex. It is used to define a regex group which we can later extract.

Output

An exception is thrown complaining about an unclosed group since it was expecting a group to be defined using the parentheses. This time the exception is java.util.regex.PatternSyntaxException: Unclosed group near index 1. Just like the square bracket, we also need to escape the round bracket like “\\(” in order to match it literally.

Output

We need to escape all metacharacters in such a way wherever we are using the regex, for example, in the string split method, string replaceAll method, and while compiling a pattern.

If you want to learn more about the regex, 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 *