Reputation: 31724
I have a String say:
<encoded:2,Message request>
Now I want to extract 2
and Message request
from the line above.
private final String pString = "<encoded:[0-9]+,.*>";
private final Pattern pattern = Pattern.compile(pString);
private void parseAndDisplay(String line) {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
while(matcher.find()) {
String s = matcher.group();
System.out.println("=====>"+s);
}
}
}
This doesn't retrieve it. What is wrong with it
Upvotes: 1
Views: 3202
Reputation: 135992
try
String s = "<encoded:2,Message request>";
String s1 = s.replaceAll("<encoded:(\\d+?),.*", "$1");
String s2 = s.replaceAll("<encoded:\\d+?,(.*)>", "$1");
Upvotes: 3
Reputation: 152206
You have to define groups in your regex:
"<encoded:([0-9]+),(.*?)>"
or
"<encoded:(\\d+),([^>]*)"
Upvotes: 6
Reputation: 7804
Try this out :
Matcher matcher = Pattern.compile("<encoded:(\\d+)\\,([\\w\\s]+)",Pattern.CASE_INSENSITIVE).matcher("<encoded:2,Message request>");
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
Upvotes: 0
Reputation: 10030
Try
"<encoded:([0-9]+),([^>]*)"
Also, as suggested in other comments, use group(1)
and group(2)
Upvotes: 0