ip地址的python正则匹配规则
IP地址的Python正则匹配规则:
import re
ipv4_pattern = r'^((([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.){3}([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))$'
ipv6_pattern = r'^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$'
ipv4_address = "192.0.2.1"
ipv6_address = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
ipv4_match = re.match(ipv4_pattern, ipv4_address)
ipv6_match = re.match(ipv6_pattern, ipv6_address)
if ipv4_match:
print("IPv4 address matched.")
else:
print("IPv4 address not matched.")
if ipv6_match:
print("IPv6 address matched.")
else:
print("IPv6 address not matched.")
该代码使用了两个正则表达式,分别用于匹配IPv4地址和IPv6地址。IPv4的正则表达式使用了分组和量词,可以匹配0-255之间的数字。IPv6的正则表达式较长,但是可以匹配所有IPv6地址
原文地址: https://www.cveoy.top/t/topic/fpJ5 著作权归作者所有。请勿转载和采集!