Java IP Address (IPv4) Regex ExamplesIP address are the unique numerical identifiers of each devices connected to a network. The first version of the IP addresses is a 32-bit address separated by period (.). In Java, Regex or Regular Expression is an API that defines the string patterns. It is widely used for searching, validating, and manipulating string and passwords. In this section, we will learn how to validate IP address with regular expression (regex). IP Address Validation Rules
ExampleInput: str = "172.16.254.1" Output: True Input: str = "000.123.12.23.28" Output: False Input: str = "I.Am.not.an.ip" Output: False Regular Expression for IP AddressGet the String. Create a regular expression to validate an IP address. // regular expression to validate numbers from 0 to 255 zeroTo255 -> (\\d{1, 2}|(0|1)\\d{2}|2[0-4]\\d|25[0-5]) //regular expression to validate complete IP address IPAddress -> zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255;
In order to match the pattern Java Pattern class provides the matcher() function. The method creates a patten that matches he given input against this pattern. It returns true if the string matches with the given regex, else return false. Syntax:Note: There may be more than one regular expression to validate IP addresses.Some Other Regular Expression for IP Addresses\b(([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\.([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\.([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\.(2[0-5][0-5]|1[0-9][0-9]|[1-9][0-9]|[1-9]))\b ^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$ Let's create a Java program that validates the IP addresses. ValidateIPAddress.java Output: Input: 172.16.254.1 Output: true Input: 111.234.162.100 Output: true Input: 000.129.24.231.89 Output: false Input: ab.cd.nef.gh.jk Output: false Next TopicConverting Long to Date in JAVA |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India