Let's check ip addresses in Java with regex
- First of all we need to import 2 library.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
- Now, lets define ip regex
public static final String IP_REGEX ="^"
+ "([01]?\\d\\d?|2[0-4]\\d|22[0-3])\\."
+ "([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-4])$";
^->行首
(->第1组的开始
[01]?\d\d? --> Can be one or two digits. If three digits appear, it must start either 0 or 1 #例如([0-9],[0-9] [0-9],[0-1] [0-9] [0-9])
| ->或
2 [0-4] \ d#以2开头,后跟0-4并以任意数字结尾(2 [0-4] [0-9])
| ->或
25 [0-5]#以2开头,后跟5并以0-5结尾(25 [0-5])
)->第2组结束
。 ->后跟一个点“。”
....->重复3次(3x)
$->行尾
- Create an pattern object and pass regex string to it.
String ipregex = System.console().readLine(); //read input
Pattern ipPattern= Pattern.compile(IP_REGEX);
Matcher ipMatcher = ipPattern.matcher(ipregex);
- Finally we can control our result.
//Control flow
if (!ipMatcher.matches()) {
System.out.println("Yay ! ");
}
else{
System.out.println("Noooooo! ");
}
return ipregex;