Python Regex从字符串中识别IPv4地址

时间:2015-10-17 23:11:10

标签: python regex string parsing ip

我很遗憾从String中提取IPv4地址。

我的输入字符串&约束如下:

  • IPv4范围:0.0.0.0255.255.255.255
  • 字符串中可能存在/可能不存在IPv4地址
    • 有效示例:this is an ip& this is an ip 200.100.2.32
  • 字符串可以以IPv4地址开头
    • 有效示例:200.100.2.32 is an ip |输出:['200.100.2.32']
    • 无效示例:200.100.2.32is an ip |输出:[]
  • 字符串可能以IPv4地址结尾
    • 有效示例:the ip is 200.100.2.32 |输出:['200.100.2.32']
    • 无效示例:the ip is200.100.2.32 |输出:[]
  • 字符串中间可能包含IPv4地址,如果是,则IPv4地址前后会有一个空格。
    • 有效示例:the ip is 200.100.2.32 and it is ipv4 |输出:['200.100.2.32']
    • 有效示例:the ip is 200.100.2.32and it is ipv4 |输出:[]
  • 单个字符串中可能存在多个IP
    • 有效示例:200.100.2.32 100.50.1.16 |输出:['200.100.2.32', '100.50.1.16']
    • 无效示例:200.100.2.32.100.50.1.16 |输出:[]

我正在尝试为上述情况构建一个正则表达式,它们看起来相当简单,而且我无法合并所有正则表达式检查。

我一直在指这些链接上的答案:IEnumeratorLink1Link2

有人可以帮助我朝正确的方向发展吗?总结一下:

  • IPv4将在它之前有一个空格或在字符串的开头
  • 开始
  • IPv4将在字符串
  • 结束后有空格或结束
  • IPv4遵循范围:0.0.0.0255.255.255.255

代码

def find_ip(str) :
    ip_pattern = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s') # need to strengthen the regex here
    ip = re.findall(ip_pattern, str)
    return ip

1 个答案:

答案 0 :(得分:1)

正则表达式:

(?:^|\b(?<!\.))(?:1?\d\d?|2[0-4]\d|25[0-5])(?:\.(?:1?\d\d?|2[0-4]\d|25[0-5])){3}(?=$|[^\w.])

匹配example