日期:2014-05-20  浏览次数:20708 次

Java中字符串匹配
例如,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);
}

------解决方案--------------------
引用:
Quote: 引用:


public static void main(String[] args) throws Exception{
String src="abc123df12gh630hh2";
src=src.replaceAll("(\\d+)","*$1*");
System.out.println(src);
}

哇,正则大神啊,这个更简洁了。能简单解释一下后面替换的字符的含义吗,*$1*为何能通配遇到的数字呢。简单解释一下哈!

前面的(\\d+)就把匹配到的数字捕获为组1了,后面$1表示组1的内容前后加*就等于把捕获到的内容前后加*