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!

3 Answers 3

3
Pattern.compile("\"id\":(\\d+)");
Sign up to request clarification or add additional context in comments.

Comments

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+)");

Comments

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

3 Comments

That .* is going to greedy match, is it not?
@Madbreaks Yep you're right - I glossed over that part and just thought he wanted to know why it was failing to compile
Is see you fixed it, removed my -1. :) Oops, it won't let me until you edit your answer, maybe put a note in it that you fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.