如何用replaceAll方法 替换ip 地址 比如 202.96.22.5 替换成 202.096.022.005
那个正则怎么写。
------解决方案--------------------
- Java code
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); }}