Reputation: 37
I'm trying to figure out how to remove the found matches from my String. So my Code sample currently looks like this:
public void checkText() {
String helper = "985, 913, 123, SomeotherText, MoreText, MoreText";
Pattern pattern = Pattern.compile("\\b\\d{3}");
Matcher matcher = pattern.matcher(helper);
while (matcher.find()) {
String newtext = "Number: " + matcher.group() + "\n"+ newtext;
helper.replaceAll(matcher.group(),"");
}
newtext = newtext + "________________\n"+ helper;
editText.setText(newtext);
}
So my input string is: 985, 913, 123, SomeotherText, MoreText, MoreText
After running the code what I would like to see is this:
Number: 985
Number: 913
Number: 123
________________________
SomeotherText, MoreText, MoreText
Anyone can tell me whats wrong in my current code?
Upvotes: 1
Views: 663
Reputation: 16498
Since you are already using the Matcher
class you can also use the method Matcher.appendReplacement
for the replacement:
public void checkText() {
String helper = "985, 913, 123, SomeotherText, MoreText, MoreText";
Pattern pattern = Pattern.compile("\\b\\d{3}, ");
Matcher matcher = pattern.matcher(helper);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
System.out.println("Number:"+matcher.group());
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println(sb.toString());
}
Upvotes: 0
Reputation: 163207
There are a few things you could update in the code:
helper
, , ,
in the replacement leaving the comma's and the follwing spaceString newtext = "";
See a Java demo
Your code might look like:
String helper = "985, 913, 123, SomeotherText, MoreText, MoreText";
Pattern pattern = Pattern.compile("\\b\\d{3}");
Matcher matcher = pattern.matcher(helper);
String newtext = "";
while (matcher.find()) {
newtext = "Number: " + matcher.group() + "\n"+ newtext;
helper = helper.replaceAll(matcher.group() + ", ","");
}
newtext = newtext + "________________\n"+ helper;
System.out.println(newtext);
Result:
Number: 123
Number: 913
Number: 985
________________
SomeotherText, MoreText, MoreText
Upvotes: 2