Sunday, April 10, 2016

IP v4 address matcher (regex)

IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.

image
The pattern is: ^(?:(?:25[0-5]?|2[0-4]?[0-9]?|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]?|2[0-4]?[0-9]?|[01]?[0-9][0-9]?)$

Java:
public class IPv4Regex {
	static final String ipV4Pattern = "^(?:(?:25[0-5]?|2[0-4]?[0-9]?|[01]?[0-9][0-9]?)\\.){3}"
			+ "(?:25[0-5]?|2[0-4]?[0-9]?|[01]?[0-9][0-9]?)$";
	
	public static void main(String[] args) {
		System.out.println("000.123.234.245".matches(ipV4Pattern));
	}
}