gpt4 book ai didi

python - 如何通过在python中排除RFC1918私有(private)地址来匹配IPV4正则表达式模式

转载 作者:行者123 更新时间:2023-12-01 09:18:13 26 4
gpt4 key购买 nike

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())

这是查找所有 IPV4 地址的正则表达式模式,但我需要排除 RFC1918 地址。请提供建议。

最佳答案

根据this reference ,IP地址正则表达式为 \b(?: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 .

您希望避免匹配以 10 开头的 IP 地址, 192.168以及以 172 开头的特定地址范围.

使用

\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

请参阅regex demo

详细信息

  • \b - 单词边界
  • (?!10\.|192\.168\.|172\.(?:1[6-9]|2[0-9]|3[01])\.) - 如果接下来出现 RFC1918 地址“标记”,则匹配失败的负向预测:
    • 10\. -10.
    • 192\.168\. -192.168.
    • 172\.(?:1[6-9]|2[0-9]|3[01])\. -172. ,然后是 16 到 31 和 .
  • (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) - 一个八位字节正则表达式(注意非捕获组,您可以将此模式与 re.findall 一起使用,以方便的方式返回所有匹配项,无需使用 re.finditer 迭代匹配项)
  • (?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3} - 重复 3 次一个点,后跟一个八位字节
  • \b - 单词边界

Python demo :

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']

关于python - 如何通过在python中排除RFC1918私有(private)地址来匹配IPV4正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51035444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com