This is my original String named ‘response’:
String response = "attributes[{"displayName":"Joe Smith","fact":"super"},{"displayName":"Kieron Kindle","fact":"this is great"}]";
I’m trying to parse the String and extract all the id values e.g
String[0] = Joe Smith
String[1] = Kieron Kindle
Pattern idPattern = Pattern.compile("\"displayName\":(\\w)"); // regular expression
Matcher matcher = idPattern.matcher(response);
while(matcher.find()){
System.out.println(matcher.group(1));
}
When i try to print the value nothing is printed to screen (no exception)
the regex expression looks for "displayName":" as a left bracket and " as right bracket then extracts any words (\\w) between them?
Appreciate any help!
Removed the \n characters from my regex, that was a formating mistake, sorry guys!
But why have you used a
\nin your regex? That should be\". Also you have used\\wwhich matches just a single character. You need to use a quantifier with that. And aReluctant one.So, your modified regex is like this: –
But, since your
Stringcan also contain space, so you should not use\\w. It will not match a space.So, finally, you should use this regex, which matches any character in between two inverted commas, except
inverted commaitself: –With the above pattern substituted in your code, your output would be like this: –
You can read more about Regex in these tutorials: –