特殊规则IP验证
IP校验 不能以0、127及224-255开头;是正确的IPpublic 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.split("");if(ips1.length>4){throw new IllegalArgumentException("Illegal IP ["+ip+"],String ["+ips+"] given that length must less than 4");}int fip = 0;try {fip = Integer.parseInt(ips);} catch (NumberFormatException e) {throw new IllegalArgumentException("Illegal IP ["+ip+"],param ["+ips+"] 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);boolean b3 = validate(ips);boolean b4 = validate(ips);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+"] 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)(|\\d|1\\d\\d|2\\d|22))\\.)((|\\d|1\\d\\d|2\\d|25)\\.){2}(|\\d|1\\d\\d|2\\d|25)$";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);}
页:
[1]