首页 > 解决方案 > 如何匹配逗号分隔字符串中的 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"]作为结果。

标签: pythonregexip

解决方案


您想实现逗号边界(?<![^,])并且(?![^,])

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

推荐阅读