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
  • 5,926
  • 14
  • 70
  • 139

3 Answers3

3
Pattern.compile("\"id\":(\\d+)");
Madbreaks
  • 18,119
  • 7
  • 53
  • 69
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,566
  • 2
  • 33
  • 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
  • 45,145
  • 22
  • 127
  • 184