先匹配再替换,这是代码. Test.javapackage com.test;import java.util.regex.Matcher; import java.util.regex.Pattern;public class Test { public static String strModify(String ip) { StringBuffer newIp = new StringBuffer(); String[] temp = ip.split("\\."); int i = 0;
for (; i < temp.length - 1; i++) { temp[i] = "0" + temp[i]; newIp.append(temp[i]); newIp.append("."); } newIp.append(temp[i]);
return newIp.toString(); } public static void main(String[] args) { String newIp = ""; String ip = "59.55.55.255"; Pattern p = Pattern.compile("[0-9]{2}.[0-9]{2}.[0-9]{2}.[0-9]{3}"); Matcher m = p.matcher(ip); if (m.matches()) { newIp = strModify(ip); } System.out.println(newIp); }}
先匹配再替换,这是代码.
Test.javapackage com.test;import java.util.regex.Matcher;
import java.util.regex.Pattern;public class Test { public static String strModify(String ip) {
StringBuffer newIp = new StringBuffer(); String[] temp = ip.split("\\."); int i = 0;
for (; i < temp.length - 1; i++) {
temp[i] = "0" + temp[i];
newIp.append(temp[i]);
newIp.append(".");
}
newIp.append(temp[i]);
return newIp.toString();
} public static void main(String[] args) {
String newIp = "";
String ip = "59.55.55.255";
Pattern p = Pattern.compile("[0-9]{2}.[0-9]{2}.[0-9]{2}.[0-9]{3}");
Matcher m = p.matcher(ip);
if (m.matches()) {
newIp = strModify(ip);
}
System.out.println(newIp);
}}