验证IP地址,字符串匹配str.matches("[0-9a-fA-F]*"),按字符匹配
![](https://img2022.cnblogs.com/blog/608798/202211/608798-20221110230841537-466856986.png)
import java.util.*;
public class Solution {
/**
* 验证IP地址
* @param IP string字符串 一个IP地址字符串
* @return string字符串
*/
public String solve (String IP) {
//判断可能是IPV4,子串转化为数字,范围是否在0-255,且不以为0开始
//判断可能是IPV6,判断子串是否匹配[0-9a-fA-F],是否最多4位,是否有多余的0
//既不是IPV4,又不是IPV6
if(IP.indexOf(".")!=-1){
String[] subs = IP.split("\\.");
if(subs.length!=4){
return "Neither";
}
for(int i=0; i<4; i++){
if(!subs[i].matches("[0-9]*")){
return "Neither";
}
if(subs[i].startsWith("0")){
return "Neither";
}
int tmp = Integer.parseInt(subs[i]);
if(tmp>255 || tmp<=0 ){
return "Neither";
}
if(i==3){
return "IPv4";
}
}
}
else if(IP.indexOf(":")!=-1){
String[] subs = IP.split(":");
if(subs.length!=8 ||IP.endsWith(":")){
return "Neither";
}
for(int i=0; i<8; i++){
if(!subs[i].matches("[0-9a-fA-F]*")){
return "Neither";
}
if(subs[i].length()>4){
return "Neither";
}
if(subs[i].startsWith("00")|| subs[i].startsWith("000")|| subs[i].startsWith("0000")){
return "Neither";
}
if(subs[i].equals("")){
return "Neither";
}
int tmp = Integer.parseInt(subs[i],16);
if(tmp>65535 || tmp<0 ){
return "Neither";
}
if(i==7){
return "IPv6";
}
}
}else{
return "Neither";
}
return "Neither";
}
}