例如,src="abc123df12gh630hh2";要将字符串中遇到的数字前后都加上*,得到新字符串。即abc*123*df*12*..... 这样的字符串,怎么弄好呢。
------解决方案--------------------
String string = "abc123df12gh630hh2";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(string);
StringBuilder builder1 = new StringBuilder();
int index = 0;
while (m.find()) {
builder1.append(string.substring(index, m.start()));
builder1.append("*").append(m.group()).append("*");
index = m.end();
}
builder1.append(string.substring(index));
System.out.println(builder1.toString());
------解决方案--------------------
public static void main(String[] args) throws Exception{
String src="abc123df12gh630hh2";
src=src.replaceAll("(\\d+)","*$1*");
System.out.println(src);
}
------解决方案--------------------
前面的(\\d+)就把匹配到的数字捕获为组1了,后面$1表示组1的内容前后加*就等于把捕获到的内容前后加*