如何通过在python中排除RFC1918专用地址来匹配IPV4正则表达式模式
这是用于查找所有IPV4地址的正则表达式模式,但我需要排除RFC1918地址。请提供建议。此正则表达式与RFC1918中的地址匹配:如何通过在python中排除RFC1918专用地址来匹配IPV4正则表达式模式,python,regex,python-2.7,Python,Regex,Python 2.7,这是用于查找所有IPV4地址的正则表达式模式,但我需要排除RFC1918地址。请提供建议。此正则表达式与RFC1918中的地址匹配: import re text='''10.11.0.0''' pattern=re.compile(r'(\b(\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)') #pat
import re
text='''10.11.0.0'''
pattern=re.compile(r'(\b(\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)')
#pattern=re.compile(r'\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b')
matches=pattern.finditer(text)
for match in matches:
print(match.group())
可在此处找到:
要获得所需的结果,只需匹配所有IP,然后删除那些与要排除的IP匹配的IP(与您自己的示例保持一致):
请注意,如果希望列表非常庞大,也可以使用生成器理解而不是列表理解,以获得相同的结果。根据,IP地址正则表达式为
您希望避免匹配以10
、192.168
开头的IP地址和以172
开头的特定地址范围
使用
见
详细信息
-单词边界\b
-如果接下来出现RFC1918地址“标记”,则会导致匹配失败的反向前瞻:(?!10\.| 192\.168\.| 172\.(?:1[6-9]| 2[0-9]| 3[01])
-10\.
10.
-192\.168\.
192.168.
-172\(?:1[6-9]| 2[0-9]| 3[01])\
,然后是16到31和172.
-一个八位元正则表达式(注意非捕获组,您可以使用此模式与(?:25[0-5]| 2[0-4][0-9]|[01]?[0-9][0-9]?)
以方便的方式返回所有匹配,无需使用re.findall
迭代匹配)re.finditer
-3次重复一个点,后跟一个八位组(?:\。(?:25[0-5]| 2[0-4][0-9]|[01]?[0-9][0-9]?){3}
-单词边界\b
(^192\.168\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^172\.([1][6-9]|[2][0-9]|[3][0-1])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^10\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)
import re
text='''10.11.0.0', 192.168.1.1, 123.4.5.6'''
pattern=re.compile(r'(\b(\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)')
exclude=re.compile(r'(^192\.168\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^172\.([1][6-9]|[2][0-9]|[3][0-1])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^10\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)')
matches = pattern.finditer(text)
filtered = [match.group() for match in matches if not exclude.match(match.group())]
for match in filtered:
print(match)
\b(?!10\.|192\.168\.|172\.(?:1[6-9]|2[0-9]|3[01])\.)(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}\b
import re
octet = r'(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
pattern=re.compile(r"\b(?!10\.|192\.168\.|172\.(?:1[6-9]|2[0-9]|3[01])\.){0}(?:\.{0}){{3}}\b".format(octet))
text = "10.11.0.0 and here are 192.168.0.0 and 192.168.0.2 145.12.24.45"
print(pattern.findall(text)) # => ['145.12.24.45']