# 力扣468. 验证IP地址（正则表达式//字符串截取遍历判断）

## 示例1️⃣：

``````输入：IP = "172.16.254.1"

``````

## 示例2️⃣：

``````输入：IP = "2001:0db8:85a3:0:0:8A2E:0370:7334"

``````

## 示例3️⃣：

``````输入：IP = "256.256.256.256"

``````

## 示例4️⃣：

``````输入：IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:"

``````

## 示例5️⃣：

``````输入：IP = "1e1.4.5.6"

``````

## 代码一，正则表达式：

``````class Solution {
public:
string validIPAddress(string IP) {
regex i4("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])");
regex i6("([0-9a-fA-F]{1,4}\:){7}[0-9a-fA-F]{1,4}");
if (regex_match(IP, i4)) return "IPv4";
else if (regex_match(IP, i6)) return "IPv6";
else return "Neither";
}
};
``````

``````class Solution {
public:
string validIPAddress(string IP) {
if(is4(IP))return "IPv4";
else if(is6(IP))return "IPv6";
return "Neither";
}
bool is4(string IP){
vector<string>ip;
split(IP,ip,'.');
if(ip.size()!=4)return false;
for(string s:ip){
if(s.size()==0||(s.size()>1&&s[0]=='0')||s.size()>3)return false;
for(char c:s){
if(!isdigit(c))return false;
}
int digit=stoi(s);
if(digit<0||digit>255)return false;
}
return true;
}

bool is6(string IP){
vector<string>ip;
split(IP,ip,':');
if(ip.size()!=8)return false;
for(string s:ip){
if(s.size()==0||s.size()>4)return false;
for(char c:s){
if(c<'0'||c>'9'&&c<'A'||c>'F'&&c<'a'||c>'f')return false;
}
}
return true;
}
void split(string s,vector<string>&ip,char c){
stringstream ss(s);
string tmp;
while(getline(ss,tmp,c))ip.push_back(tmp);
if(s.size()>0&&s.back()==c)ip.push_back({});
}
};
//从力扣题解摘下来的，我要先休息一下。

``````

THE END