[b]IP校验 不能以0、127及224-255开头;是正确的IP
[/b]
由于对正则表达式不熟悉,以及时间原因,所以上面这是比较笨的方法,解决问题还是得自己细心,用心,精心,好多问题真的是只要自己稍微花点时间用下心,用点时间,用点力就可以解决得了!下面是正则表达式:
[/b]
public class IpReg {
public static void main(String[] args) {
String s = "225.255.255.255";
boolean b = false;
//只要捕获到了异常,说明Ip是非法的,根据需要处理异常
try {
b = validateIP(s);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("验证结果为 :"+b);
}
public static boolean validateIP(String ip){
boolean b = false;
String[] ips = ip.split("\\.");
if(ips.length!=4){
throw new IllegalArgumentException("Illegal IP ["+ip+"]");
}
//对第一组进行验证
String[] ips1 = ips[0].split("");
if(ips1.length>4){
throw new IllegalArgumentException("Illegal IP ["+ip+"],String ["+ips[0]+"] given that length must less than 4");
}
int fip = 0;
try {
fip = Integer.parseInt(ips[0]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal IP ["+ip+"],param ["+ips[0]+"] given must be type of number!");
}
//如果没有抛出异常,则全部是数字,进行判断是否合法
if(fip<0 | fip == 0 | fip == 127){
throw new IllegalArgumentException("Illegal IP ["+ip+"], can not begin with "+fip);
}else{
b = true;
for(int i=224;i<=255;i++){
if(fip==i){
throw new IllegalArgumentException("Illegal IP ["+ip+"], can not begin with "+fip);
}
}
}
//对剩下的三组进行验证
boolean b2 = validate(ips[1]);
boolean b3 = validate(ips[2]);
boolean b4 = validate(ips[3]);
return b&b2&b3&b4;
}
private static boolean validate(String subip){
String[] ips = subip.split("");
if(ips.length>4){
throw new IllegalArgumentException("Illegal IP ["+subip+"],String ["+subip+"] given that length must less than 4");
}
Integer ip = null;
try {
ip = Integer.parseInt(subip);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal IP ["+subip+"],param ["+ips[0]+"] given must be type of number!");
}
//如果没有抛出异常,则全部是数字,进行判断是否合法
if(ip<=255 && ip>-1){
return true;
}else{
throw new IllegalArgumentException("Illegal IP ["+subip+"],param ["+subip+"] given that must less than 256 and great than -1");
}
}
}
由于对正则表达式不熟悉,以及时间原因,所以上面这是比较笨的方法,解决问题还是得自己细心,用心,精心,好多问题真的是只要自己稍微花点时间用下心,用点时间,用点力就可以解决得了!下面是正则表达式:
String str_pattern = "^(((?!127)([1-9]|[1-9]\\d|1\\d\\d|2[0-1]\\d|22[0-3]))\\.)(([0-9]|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){2}([0-9]|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])$";
Pattern pattern = Pattern.compile(str_pattern);
String ip ="127.127.127.245";
Matcher m = pattern.matcher(ip);
boolean b = m.find();
if(b){
System.out.println(m.group());
}else{
System.out.println(b);
}