我试图弄清楚如何从我的String中删除找到的匹配项。因此,我的代码示例当前如下所示:
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);
}
所以我的输入字符串是:985, 913, 123, SomeotherText, MoreText, MoreText
运行代码后,我想看的是:
Number: 985
Number: 913
Number: 123
________________________
SomeotherText, MoreText, MoreText
任何人都可以告诉我当前代码有什么问题吗?
答案 0 :(得分:2)
您可以在代码中进行一些更新:
helper
, , ,
开头,并保留逗号和以下空格String newtext = "";
您的代码可能如下:
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);
结果:
Number: 123
Number: 913
Number: 985
________________
SomeotherText, MoreText, MoreText
答案 1 :(得分:0)
由于您已经在使用Matcher
类,因此也可以使用方法Matcher.appendReplacement
进行替换:
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());
}