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

我想弄清楚如何从我的字符串中删除找到的匹配项。所以我的代码示例目前看起来像这样:


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

谁能告诉我我当前的代码有什么问题?


慕少森
浏览 147回答 2
2回答

饮歌长啸

您可以在代码中更新一些内容:您应该将更换的退货设置为helper如果您只替换为空字符串,则您的字符串将, , ,在替换中以逗号和后续空格开头您可以初始化变量String newtext = "";查看Java 演示您的代码可能如下所示: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: 123Number: 913Number: 985________________SomeotherText, MoreText, MoreText

慕的地10843

由于您已经在使用该类,因此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());}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java