0

This is my original String:

String response = "attributes[{"id":50,"name":super},{"id":55,"name":hello}]";

I'm trying to parse the String and extract all the id values e.g
50
55

Pattern idPattern = Pattern.compile("{\"id\":(.*),");
Matcher matcher = idPattern.matcher(response);

while(matcher.find()){
    System.out.println(matcher.group(1));
}


When i try to print the value i get an exception: java.util.regex.PatternSyntaxException: Illegal repetition
Not had much experience with regular expressions in the past but cannot find a simple solution to this online.
Appreciate any help!

bobbyrne01
  • 6,295
  • 19
  • 80
  • 150

3 Answers3

3
Pattern.compile("\"id\":(\\d+)");
Madbreaks
  • 19,094
  • 7
  • 58
  • 72
2

{ is a reserved character in regular expressions and should be escaped.

\{\"id\":(.*?),

Edit : If you're going to be working with JSON, you should consider using a dedicated JSON parser. It will make your life much easier. See Parsing JSON Object in Java

Community
  • 1
  • 1
Mike Park
  • 10,845
  • 2
  • 34
  • 50
2

Don't use a greedy match operator like * with a . which matches any character. unnecessarily. If you want the digits extracted, you can use \d.

"id":(\d+)

Within a Java String,

Pattern.compile("\"id\":(\\d+)");
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191