特殊ルールIP検証
IP検査は0、127及び224-255で始まることができない.正しいIPです
正则の表现に対して熟知していないため、および时间の原因、だから上のこれは比较的に愚かな方法で、问题を解决するのはやはり自分で注意深くて、心を込めて、多くの问题は本当に自分が少し时间をかけて心を使うのでさえすれば、少し时间を使って、少し力を使って解决することができます!次は正規表現です.
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);
}