如何在python中使用正则表达式验证IPv4和IPv6

时间:2017-10-30 06:18:53

标签: python regex

如果有任何更正或改进,请发表评论

#For IPv6

import re
text='''FE80:CD00:0:0:0:0:211E:729C FE80:CD00:0:CDE:1257:0:211E:729C 
bE80:Cc00:0:0:0:0:211E:727C dFE80:Ca00:0:0:0:0:211E:7295'''  
pattern=re.compile(r'([0-9a-fA-F]{0,4}:){7}[0-9a-fA-F]{0,4}')

matches=pattern.finditer(text)

for match in matches:
    print(match)

对于IPv4

import re
ip='''
1.
255.255.222.199 
255.255.222.255 199.244
111.
169.
99.
999.
256.
'''

pattern=re.compile(r'([\d]|[\d]{2}|[1][\d]{2}|[2][0-5]{2})\.([\d]|[\d]{2}|[1][\d]{2}|[2][0-5]{2})\.([\d]|[\d]{2}|[1][\d]{2}|[2][0-5]{2})\.([\d]|[\d]{2}|[1][\d]{2}|[2][0-5]{2})\b')


matches=pattern.finditer(ip)

for match in matches:

    print(match)

如果有任何更正或改进,请发表评论

0 个答案:

没有答案
相关问题