Reputation: 6745
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!
Upvotes: 0
Views: 2793
Reputation: 213261
But why have you used a \n
in your regex? That should be \"
. Also you have used \\w
which matches just a single character. You need to use a quantifier with that. And a Reluctant one
.
So, your modified regex is like this: -
Pattern.compile("\"displayName\":\"(\\w+?)\""); // This won't consider space
But, since your String
can 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 comma
itself: -
Pattern.compile("\"displayName\":\"([^\"]+)\"");
With the above pattern substituted in your code, your output would be like this: -
"Joe Smith"
"Kieron Kindle"
You can read more about Regex in these tutorials: -
Upvotes: 1
Reputation: 32797
You should use this regex
\"displayName\":\"(.*?)\"
(.*?)
matches 0 to many characters
OR[correcting your regex]
\"displayName\":\"([\w\s]+)\"
([\w\s]+)
matches a word i.e \w
or a space i.e \s
1 to many times i.e +
Group1
now has the data
Upvotes: 0