Java正则表达式从字符串中删除匹配项

时间:2019-07-11 12:20:41

标签: java regex

我试图弄清楚如何从我的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

任何人都可以告诉我当前代码有什么问题吗?

2 个答案:

答案 0 :(得分:2)

您可以在代码中进行一些更新:

  • 您应将替换项的返回值设置为helper
  • 如果仅用空字符串替换,则替换后的字符串将以, , ,开头,并保留逗号和以下空格
  • 您可以初始化变量String newtext = "";

查看Java demo

您的代码可能如下:

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());
}