Solution – java.util.regex.PatternSyntaxException: Illegal repetition

Solution – java.util.regex.PatternSyntaxException: Illegal repetition example shows what causes this exception and how to solve or fix it.

What causes the java.util.regex.PatternSyntaxException: Illegal repetition exception?

As the exception message says “illegal repetition”, this exception is thrown when we use the repetition meta-characters with the invalid range values in the regex pattern.

The opening and closing curly brackets, i.e. “{” and “}”, are used to define a repetition of the previous expression in a pattern. For example, if the pattern is “\\d{1,2}”, it means any digit 1 or 2 times.

The first number inside the curly brackets is the minimum times the previous expression should match, while the second number specifies the maximum. We can also specify a single number to specify an exact number of matches like “\\d{2}”. This pattern will match a number with exactly 2 digits.

Now coming back to the exception. The most common reason for this exception is when we try to replace the “{” with something else in the string using the replaceAll method as given below.

Output

The replaceAll method accepts a regex pattern to replace the content in the string so “{” is considered as a regex pattern. Since the “{” is used to define the repetition in regex, it looks for the number(s) inside it. Since there are no numbers, the syntax for the repetition is invalid and it throws this exception.

Solution:

Escape all opening curly brackets. In order to treat “{” as a literal instead of a regex pattern, we need to escape it like “\{“. See the below example.

Output

This exception is also thrown by the string split method, as like the replaceAll method, it also accepts a regex pattern parameter.

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