This has been one of the popular programming tasks for Java developer, particularly focusing on text processing.
IPv4 addresses may be represented in any notation expressing a 32-bit integer value. They are most often written in the dot-decimal notation, which consists of four octets of the address expressed individually in decimal numbers and separated by periods.
For example, the quad-dotted IP address 172.16.255.1.
Here is a program to match Internet Protocol version 4 (IPv4) address:
public class IpAddressMatcher { private static String pattern= "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; private final Pattern regexPattern = Pattern.compile(pattern); public boolean isValidIp(final String ip) { Matcher matcher = regexPattern.matcher(ip); return matcher.matches(); } @Test public void testIsValidIp() { assertTrue(isValidIp("000.12.12.034")); assertTrue(isValidIp("121.234.12.21")); assertTrue(isValidIp("23.45.12.65")); assertTrue(isValidIp("0.1.2.3")); assertFalse(isValidIp("666.666.23.23")); assertFalse(isValidIp(".12.32.232.23")); } }
All source code is available on GitHub. Cheers!!