468. 验证IP地址 + 正则表达式 + 模拟题
468. 验证IP地址
LeetCode_468
题目描述
方法一:正则表达式
import java.util.regex.*;
class Solution {
//Ipv4的正则匹配表达式
String regIpv4 = "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";//注意要加括号
Pattern patternIpv4 = Pattern.compile("^(" + regIpv4 + "\\.){3}" + regIpv4 + "$");
//Ipv6的正则匹配表达书
String regIpv6 = "([0-9a-fA-F]{1,4})";//注意要加括号
Pattern patternIpv6 = Pattern.compile("^(" + regIpv6 + "\\:){7}" + regIpv6 + "$");
public String validIPAddress(String IP) {
if(IP.contains(".")){
return (patternIpv4.matcher(IP).matches()) ? "IPv4" : "Neither";//用ipv4的正则表达式去匹配输入的IP地址
}else if(IP.contains(":")){
return (patternIpv6.matcher(IP).matches()) ? "IPv6" : "Neither";//用ipv6的正则表达式去匹配输入的IP地址
}else return "Neither";
}
}
方法二:模拟
Either Excellent or Rusty