package others;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 判断IP地址是否合法
* @author YangXian
*
*/
/*
* 所有的一位数(1): \d
* 所有的二位数(2): [1-9]\d
* 1开头的三位数(所有)(3): 1\d{2}
* 2开头的三位数(200-255)(4): 2[0-4]\d|25[0-5]
*
* 每个数可能为(format): ^((1)|(2)|(3)|(4))
* 总规则为: ^(format)(\.(format)){3}$
*
* 最终规则: ^(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}$
*
*/
public class IPCheck {
public static boolean ipCheck(String str) {
if( str != null && !str.isEmpty()){
String pattern = "^(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$";
//String regex="^([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$";
if(str.matches(pattern))
return true;
return false;
}
return false;
}
public static void main(String[] args) {
System.out.println(ipCheck("192.168.0.1"));
System.out.println(ipCheck("256.168.0.1"));
}
}