IP Address Regex 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])$
^ | Start of line |
( | Start of group |
[01]?\\d\\d? | Can be one or two digits. If three digits appear, it must start either 0 or 1 |
2[0-4]\\d | start with 2, follow by 0-4 and end with any digit |
25[0-5] | start with 2, follow by 5 and end with 0-5 (25[0-5]) |
) | End of group |
\. | follow by a dot |
$ | end of the line |
Example
package mycollectiontest;Output
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
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 RegexExample() {
pattern = Pattern.compile(IPADDRESS_PATTERN);
String input = "12.12.12";
System.out.println("input : " + input + " " + validate(input));
String input1 = "180.151.46.166";
System.out.println("input : " + input1 + " " + validate(input1));
}
public boolean validate(final String username) {
matcher = pattern.matcher(username);
return matcher.matches();
}
public static void main(String[] args) {
new RegexExample();
}
}
input : 12.12.12 false
input : 180.151.46.166 true
No comments:
Post a Comment