Reference:
[1] https://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/
Import Java.util.regex.matcher;import Java.util.regex.pattern;public class ipaddressvalidator{ private Pattern pattern; Private Matcher Matcher; private static final String Ipaddress_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]) $ "; Public Ipaddressvalidator () { pattern = pattern.compile (Ipaddress_pattern); } /** * Validate IP address with regular expression * @param IP IP address for validation * @return true valid I P address, false invalid IP address * /public Boolean validate (final String IP) { matcher = Pattern.matcher (IP); return matcher.matches (); }}
Description
^ #start of the line (# start of group #1 [01]?\\d\\d? # Can be one or both digits. If three digits appear, it must start either 0 or # e.g ([0-9], [0-9][0-9],[0-1][0-9][0-9]) |# ... or 2[0- 4]\\d# start with 2, follow by 0-4 and end with any digit (2[0-4][0-9]) | # ... or 25[0-5] # start with 2, follow by 5 and ends with 0-5 (25[0-5])) # End of group #2 \ . # follow by a dot "." .... # Repeat with 3 times (3x) $ #end of the line
Whole combination means, digit from 0 to 255 and follow by a dot ".", repeat 4 time and ending with no dot "." Valid IP address format is "0-255.0-255.0-255.0-255"
Java Regex Match IP address