Java/JS校验IP(IPv4网段)正则表达式

Java正则校验:

public static void main(String[] args) {

		String ipReg = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[0-9]\\d|[0-9])\\."
	            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[0-9]\\d|\\d)\\."
	            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[0-9]\\d|\\d)\\."
	            + "(\\*)$";
		
		String ipReg2 = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[0-9]\\d|[0-9])\\."
	            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[0-9]\\d|\\d)\\."
	            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[0-9]\\d|\\d)\\."
	            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[0-9]\\d|\\d)$";

		Pattern ipPattern = Pattern.compile(ipReg);
		Pattern ipPattern2 = Pattern.compile(ipReg2);

		boolean flag = ipPattern.matcher("0.0.0.*").matches();
		System.out.println(flag);
		flag = ipPattern.matcher("0.0.0.0").matches();
		System.out.println(flag);
		flag = ipPattern2.matcher("255.255.255.256").matches();
		System.out.println(flag);
		flag = ipPattern2.matcher("0.0.0.0").matches();
		System.out.println(flag);
	}

运行结果:

Java/JS校验IP(IPv4网段)正则表达式_第1张图片

 

JS正则校验:

 

function checkIp(){
	var ip = $("#send_ip").val();
	var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
	if(reg.test(ip)){
		alert( "ip("+ip+")合规" );
	}else{
		alert( "ip("+ip+")不合规" );
		return;
	}
}

 

你可能感兴趣的:(Java/JS校验IP(IPv4网段)正则表达式)