日期:2014-05-20 浏览次数:21036 次
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test6 { public static void main(String[] args) { String str = "222.96.22.5"; // 方法 1(推荐) Pattern pattern = Pattern.compile("(?<=^|\\.)(?:(\\d{2})|(\\d))(?!\\d)"); Matcher matcher = pattern.matcher(str); StringBuffer sb = new StringBuffer(); while (matcher.find()) { if (matcher.start(1) > 0) { matcher.appendReplacement(sb, "0$1"); } else if (matcher.start(2) > 0) { matcher.appendReplacement(sb, "00$2"); } } matcher.appendTail(sb); System.out.println(sb.toString()); // 方法 2 str = str.replaceAll("(?<=^|\\.)(\\d{1,2})(?!\\d)", "0$1") .replaceAll("(?<=^|\\.)(\\d{2})(?!\\d)", "0$1"); System.out.println(str); } }