一个简单的java题求解?

来源:百度知道 编辑:UC知道 时间:2024/09/20 16:55:40
Pattern p=Pattern.compile("(\\b\\d{1,3}\\b)");
Matcher m = p.matcher(str);

StringBuffer sb = new StringBuffer();
//数字段缓存
StringBuffer group=new StringBuffer();

//替换开始
while (m.find()) {
//清空缓存
group.delete(0,group.length());
group.append(m.group());
//不足三位补齐
while(group.length()<3){
group.insert(0,'0');
}
m.appendReplacement(sb, group.toString());
}
m.appendTail(sb);

return sb.toString();
}

其中appendReplacement和appendTail方法起什么作用呀,请帮我详细说明一下

这个方法我不见过,

根据字面意思推测下,appendReplacement 应该是把后面的替换掉。

appendTail 不知道什么意思,

建议参考API文档

public Matcher appendReplacement(StringBuffer sb,
String replacement)
将正则表达式Matcher m = p.matcher(str);中配匹的字符,用replacement这个字符串替换,你的程序也就是group.toString()这个字符串,如API中的例子一样,appendTail()应该是从追加位置开始从输入序列读取字符,并将其追加到给定字符串缓冲区。可以在一次或多次调用 appendReplacement 方法后调用它来复制剩余的输入序列。

Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());

结果应该为:one dog two dogs in the yard
不知道说没说明白.

貌似replacement是一段段替换并复制到sb里的,tail就是把剩余部分复制进去