package test;
public class Regex {
public static void main(String[] args) {
System.out.println(ipCheck("192.168.12.231"));
}
/**
* 驗證ip是否合法
*
* @param text
* ip地址
* @return 驗證信息
*/
public static String ipCheck(String text) {
if (text != null && !text.isEmpty()) {
// 定義正則表達式
String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
// 判斷ip地址是否與正則表達式匹配
if (text.matches(regex)) {
// 返回判斷信息
return text + "\n是一個合法的IP地址!";
} else {
// 返回判斷信息
return text + "\n不是一個合法的IP地址!";
}
}
// 返回判斷信息
return "請輸入要驗證的IP地址!";
}
}
