题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
//正则表达式 #include <regex> class Solution { public: /** * 验证IP地址 * @param IP string字符串 一个IP地址字符串 * @return string字符串 */ string solve(string IP) { // write code here //ipv4:0-255,没有先导0,不可缺省、必须为数字 regex ipv4("(([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])"); //ipv6:0-9a-fA-F的数,个数必须是1-4个 regex ipv6("([0-9a-fA-F]{1,4}\\:){7}([0-9a-fA-F]{1,4})"); if(regex_match(IP,ipv4)) return "IPv4"; else if (regex_match(IP,ipv6)) { return "IPv6"; } else { return "Neither"; } } };