正则表达式仅匹配范围内的第二个 IP 地址

问题描述 投票:0回答:3

我试图仅将字符串中的第二个有效 IP 地址与一系列 IP 地址进行匹配。有时,地址之间没有空格,而某些地址之间有一个或多个空格。有时 IP 无效,因此不应该匹配。

test = '''
1.0.0.0-1.0.0.240
2.0.0.0 - 1.0.0.241
3.0.0.0 -1.0.0.242
4.0.0.0- 1.0.0.243
5.0.0.0  -  1.0.0.244
6.0.0.0 -  1.0.0.245
7.0.0.0 -  1.0.0.2456 #NOT VALID SO DONT MATCH
'''

pattern = r"(?<=-\s))\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
r = re.compile(pattern, re.DOTALL)
print(r.findall(test))

我的尝试仅捕获:1.0.0.241 和 1.0.0.243

python python-3.x regex regex-lookarounds
3个回答
0
投票

将正则表达式模式更改为以下内容:

pattern = r"(?<=[-\s])((?:\d{1,3}\.){3}\d{1,3})$"
r = re.compile(pattern, re.M)
print(r.findall(test))

['1.0.0.240', '1.0.0.241', '1.0.0.242', '1.0.0.243', '1.0.0.244', '1.0.0.245']

0
投票

您可以在模式末尾添加

\D
,以确保最后 3 位数字后面不会跟着第四位数字。然而,这仍然不能确保点之间的数字在 0-255 范围内。


0
投票

这应该与您的所有示例相匹配:

pattern = r"^.*\s*-\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$"
r = re.compile(pattern)
print(r.findall(test))

您也可以通过群组功能获取第二个IP。

© www.soinside.com 2019 - 2024. All rights reserved.