Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PatternSyntaxException: Illegal Repetition when using regex in Java

People also ask

What is Java util regex PatternSyntaxException?

The java. util. regex. PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern.

Can you use regex in Java?

Regular expressions can be used to perform all types of text search and text replace operations. Java does not have a built-in Regular Expression class, but we can import the java. util. regex package to work with regular expressions.

How does regex Java work?

It works as the combination of compile and matcher methods. It compiles the regular expression and matches the given input with the pattern. splits the given input string around matches of given pattern. returns the regex pattern.

What is the purpose of Matcher class used for regular expression?

Matcher Class − A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors.


The { and } are special in Java's regex dialect (and most other dialects for that matter): they are the opening and closing tokens for the repetition quantifier {n,m} where n and m are integers. Hence the error message: "Illegal repetition".

You should escape them: "\\{\"user_id\" : [0-9]*\\}".

And since you seem to be trying to parse JSON, I suggest you have a look at Jackson.


There should be plus operator:

user_id : [0-9]+

Double apostrophes only when the string has to contain it.

When the string including curly brackets use:

\{user_id : [0-9]+\}