2 回答
TA贡献1951条经验 获得超3个赞
您可以在代码中更新一些内容:
您应该将更换的退货设置为
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: 123
Number: 913
Number: 985
________________
SomeotherText, MoreText, MoreText
TA贡献1785条经验 获得超8个赞
由于您已经在使用该类,因此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());
}
添加回答
举报