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

正则表达式问题,替换所有数字,为非常长的数字,超难
如:1-abc-w154e944
找到所有的连续数字,使之变长(例如6位,不足的前面补0)
执行结果:000001-abc-w000154e000944

用正则表达式实现

------解决方案--------------------
Java code

        Pattern pattern = Pattern.compile("(\\d+)");
            Matcher matcher = pattern.matcher("1-abc-w154e944");
            StringBuffer sbf = new StringBuffer();
            while(matche.find()){
                StringBuffer zero = new StringBuffer();
                for(int i = (6 - matcher.group().length());i>0;i--){
                    zero.append("0");
                }
                matcher.appendReplacement(sbf,zero+matcher.group());
            }
            matcher.appendTail(sbf);
            System.out.println(sbf);

------解决方案--------------------
for example
Java code
String str = "1-abc-w154e944";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
StringBuffer buf = new StringBuffer();
while (m.find()) {
    String s = String.format("000000%s", m.group());
    m.appendReplacement(buf, s.substring(s.length()-6));
}
m.appendTail(buf);
System.out.println(buf);