题目链接:468. 验证IP地址
用正则判断。
import re
class Solution:
@staticmethod
def is_ipv4(queryIP: str) -> bool:
m = re.fullmatch(r'(\d+)\.(\d+)\.(\d+)\.(\d+)', queryIP)
if m is None:
return False
return all(0 <= int(i) <= 255 and str(int(i)) == i for i in m.groups())
@staticmethod
def is_ipv6(queryIP: str) -> bool:
return re.fullmatch(r'[\da-fA-F]{1,4}(:[\da-fA-F]{1,4}){7}', queryIP) is not None
def validIPAddress(self, queryIP: str) -> str:
if self.is_ipv4(queryIP):
return 'IPv4'
if self.is_ipv6(queryIP):
return 'IPv6'
return 'Neither'