如何在字符串中查找IP模式

2024-03-28 23:50:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到一个IP模式或任何类似的模式在一个字符串。例如:

Text_1 = "Hello this ip is valid: 123.22.33.22 , but!" #expect 123.22.33.22

Text_2 = "this could be the second valid ip: 323.123.22.33.22 , but!" #expect 323.123.22.33.22

Text_3 = "third pattern is: 01.002.33.222 , but!" #expect 01.002.33.222

Text_4 = "fourth pattern is: 332.332.222 , but!" #expect 332.332.222

在所有情况下,我都需要提取所有由点分隔的数字,然后评估它们是否可能有效。你知道吗

我看过this问题和this问题,但都有一些问题!你知道吗

这是我发现的,但并不完美,因为它无法捕捉长度超过4位的字符串:

import re
re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', s).group()

Tags: 字符串textiprehellois模式be
3条回答

怎么样:map(int,“167.78.2.99”.split(“.”))(split by。并尝试将每个元素转换为整数)并检查类型错误,检查len()是否为4,检查每个元素0<;=el<;256。你知道吗

对不起,没有密码,我的电脑没有

如果您想要任何数字和点的序列,请尝试以下操作:

# Find a number, then one or more ".numbers"
re.search(r'(\d+)(\.(\d+))+', Text_2).group()

它给出:

'323.123.22.33.22'

注意:提取候选项后,可以使用this answer提供的regex检查它。你知道吗

这将查找确切的ip地址:

^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$

https://regex101.com/r/3biYkC/1

更新时,我添加了一个词boundry到它,它似乎工作:

\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}\b

https://regex101.com/r/3biYkC/2

相关问题 更多 >