如何匹配以逗号分隔的字符串中的 IP 地址 [英] How to match IP addresses in a comma-separated string

查看:82
本文介绍了如何匹配以逗号分隔的字符串中的 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码显示如下,但有问题:255.255.255.256";将被处理为255.255.255.25"

Code show as below, but there is a problem: "255.255.255.256" will be processed into "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"] 作为结果.>

If I pass the 255.255.255.255,255.255.255.256,260.255.255.255 string I expect ["255.255.255.255"] as the results.

推荐答案

您想要实现逗号边界(?<![^,]) 和 <代码>(?![^,]):

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 匹配一个位置,前面没有一个字符而不是逗号(即必须有一个逗号或字符串的开头)当前位置的左侧)
  • (?![^,]) - 一个负向前瞻,匹配一个位置后没有紧跟一个除逗号以外的字符(即必须有一个逗号或字符串结尾紧跟当前位置的右侧).
  • (?<![^,]) - a negative lookbehind that matches a location not immediately preceded with a char other than a comma (i.e. there must be a comma or start of string immediately to the left of the current location)
  • (?![^,]) - a negative lookahead that matches a location not immediately followed with a char other than a comma (i.e. there must be a comma or end of string immediately to the right of the current location).

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

这篇关于如何匹配以逗号分隔的字符串中的 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆