python - 如何匹配逗号分隔字符串中的 IP 地址
问题描述
代码如下,但是有一个问题:“255.255.255.256”会被处理成“255.255.255.25”
import re
ip_pattern = re.compile(r"((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)")
def get_ip_by_regex(ip_str):
"""Match IP from the given text and return
:param ip_str: like "255.255.255.255,255.255.255.256,260.255.255.255"
:type ip_str: string
:return: IP LIST ["255.255.255.255"]
:rtype: list[string]
"""
ret = []
for match in ip_pattern.finditer(ip_str):
ret.append(match.group())
return ret
如果我传递255.255.255.255,255.255.255.256,260.255.255.255
我期望的字符串["255.255.255.255"]
作为结果。
解决方案
您想实现逗号边界,(?<![^,])
并且(?![^,])
:
ip_pattern = re.compile(r"(?<![^,])(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?![^,])")
请参阅正则表达式演示。
细节
(?<![^,])
- 一个否定的lookbehind,它匹配一个不是逗号之前的字符的位置(即当前位置的左边必须有一个逗号或字符串开头)(?![^,])
- 与不紧跟逗号以外的字符的位置匹配的负前瞻(即,当前位置右侧必须有一个逗号或字符串结尾)。
请参阅Python 演示:
import re
ip_pattern = re.compile(r"(?<![^,])(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?![^,])")
def get_ip_by_regex(ip_str):
"""Match IP from the given text and return
:param ip_str: like "255.255.255.255,255.255.255.256,260.255.255.255"
:type ip_str: string
:return: IP LIST ["255.255.255.255"]
:rtype: list[string]
"""
return ip_pattern.findall(ip_str)
print(get_ip_by_regex('255.255.255.255,255.255.255.256,260.255.255.255'))
# => ['255.255.255.255']
推荐阅读
- angular - 专注于引导模式内的输入字段在角度 6 中没有发生
- rest - 使用 JWT 从 API Rest 获取数据的代码(使用 Post 和 Get 方法)
- python - 如何在捕获组中抓取多个段落?
- c# - 准备好在 HTML 上执行 Javascript
- ios - 如何在超级视图的控制器中处理子视图的手势事件?
- mysql - find_in_set 和 find_in_set 意外结果
- java - randomFill() 函数未定义
- python - Random TimeoutException 即使在使用 ui.WebDriverWait() chrome selenium python 之后
- ios - 如何从 iOS 上的其他应用打开 Google Play 音乐应用?
- javascript - jQuery一次禁用多个属性