This example describes the regular expression validation IPV4 address feature. Share to everyone for your reference, as follows:
The IPV4 address consists of 4 groups of numbers, separated by a., and the range of values for each group of numbers is 0-255.
IPV4 must meet the following four rules:
1. Any 1-digit or 2-digit number, or 0-99;
2. Any 3-digit number starting with 1, or 100-199;
3, any one starting with 2, the 2nd digit is 0-4 between 3 digits, that is, 200-249;
4, any one beginning with 25, the 3rd digit in the 0-5 between the 3 digits, namely 250-255.
The idea of constructing a regular expression is clear after all the rules are listed.
The first rule that satisfies the first one is: \d{1,2}
The first rule that satisfies the second one is: 1\d{2}
The first rule that satisfies the third one is: 2[0-4]\d
The first rule that satisfies fourth rules is: 25[0-5]
By grouping them together, you get a regular expression that matches 0-255 numbers:
(\d{1,2}) | (1\d{2}) | (2[0-4]\d) | (25[0-5])
The IPV4 consists of four groups of numbers, separated by., or by three numbers and characters. And a set of numbers, so the regular expression that matches the IPV4 is as follows:
((\d{1,2}) | (1\d{2}) | (2[0-4]\d) | (25[0-5])) \.) {3} ((\d{1,2}) | (1\d{2}) | (2[0-4]\d) | (25[0-5]))
The Java test code is as follows:
public static void Matchandprint (string regex, String sourcetext) { Pattern pattern = pattern.compile (regex); Matcher Matcher = Pattern.matcher (sourcetext); while (Matcher.find ()) { System.out.println (Matcher.group ());} } public static void Main (string[] args) { String regex = "^ ((\\d{1,2}) | ( 1\\D{2}) | (2[0-4]\\d) | (25[0-5])) \\.) {3} ((\\d{1,2}) | (1\\d{2}) | (2[0-4]\\d) | (25[0-5])) $"; Matchandprint (Regex, "23.135.2.255"); Matchandprint (Regex, "255.255.0.256"); Matchandprint (Regex, "0.0.0.0");}
The output results are as follows:
23.135.2.255
0.0.0.0
This regular has a flaw, that is, if you do not use boundary matching, like the second Test IP 255.255.0.256 will also be matched to the result of matching is 255.255.0.25. You can add a constraint, either before or after a boundary, or a non-numeric, and use the front and back lookup (Lookaround), which is described later. That
(? <= (\\b|\\d)) ((\d{1,2}) | (1\d{2}) | (2[0-4]\d) | (25[0-5])) \.) {3} ((\d{1,2}) | (1\d{2}) | (2[0-4]\d) | (25[0-5])) (? = (\\b|\\d))
String regex = "(? <= (\\b|\\d)) ((\\d{1,2}) | ( 1\\D{2}) | (2[0-4]\\d) | (25[0-5])) \\.) {3} ((\\d{1,2}) | (1\\d{2}) | (2[0-4]\\d) | (25[0-5])) (? = (\\b|\\d)) ";
This solves the problem.
It is hoped that this article will be helpful to everyone's regular expression learning.