一个我做不不出来的题。帮下啦!
59.55.55.255 如何用java中的正则表达式让这个IP地址格式。改成这种形式啊059.055.055.255。
注:一定要用正则!
------解决方案--------------------
[code=Java][/code]
先匹配再替换,这是代码.
Test.java
package 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);
}
}