python - 如果 x != 0,则不带 0.x.x.x 的 ipv4 地址的正则表达式

标签 python regex

我正在为 ipv4 地址做一个正则表达式,非常有趣的是 Ubuntu 和一些 RFC 引用文献指出 0.x.x.x 如果 x != 0 被保留,所以无效。对此更优化的正则表达式应该是什么?我有这个:

import re
matcher = re.compile(r'^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]|[1-9])(\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])){3}\Z^(0)(.0){3}\Z')

例如:

0.1.2.3 => should be invalid
1.0.0.0 => should be valid
0.0.0.0 => should be valid

最佳答案

这是满足要求的正则表达式:

^(?!0+(?:\.0*[1-9][0-9]*){3}$)(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$

参见its online demo .

要点是:

  • (?!0+(?:\.0*[1-9][0-9]*){3}$) - 一个 (?!... ) 是一个否定的前瞻,如果其模式匹配,则匹配失败:
    • 0+ - 1+ 个零
    • (?:\.0*[1-9][0-9]*){3} - 连续出现 3 次
    • \. - 一个点
    • 0* - 0+ 个零
    • [1-9] - 从 19 的数字
    • [0-9]* - 任意 0+ 位数字
    • $ - 字符串结尾。

此外,八位字节正则表达式现在也匹配 0:

  • (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):
    • 25[0-5]| - 250 直到 255
    • 2[0-4][0-9]| - 200 直到 249
    • [01]?[0-9][0-9]? - 10(可选,1 次或 0 次) 然后任意数字,然后任意 1 或 0 数字(可选数字)。

一个Python demo :

import re

rx = """(?x)^   # start of string
         (?!    # start of the negative lookahead that fails the match if 
            0+(?:\.0*[1-9][0-9]*){3}$  # 0s appear only in the first octet
         )      # end of the lookahead
         (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)  # First octet regex
         (?:    # start of the non-capturing group
            \.  # a dot
            (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # octet
         ){3}   # repeated 3 times
         $      # end of string
"""
lst = ['0.1.2.3','1.0.0.0','0.0.0.0']
for s in lst:
    m = re.match(rx, s)
    if m:
        print("{} matched!".format(s))
    else:
        print("{} did not match!".format(s))

输出:

0.1.2.3 did not match!
1.0.0.0 matched!
0.0.0.0 matched!

关于python - 如果 x != 0,则不带 0.x.x.x 的 ipv4 地址的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47062663/

相关文章:

python - 从矩阵数据框中提取组合列表及其计数值?

c# - 这个正则表达式的名称是什么?

javascript - 从谷歌地理编码结果中删除奇怪的日文字符

python - 如何测试使用 exec_() 调用的自定义对话框窗口?

python - 给定一个完全由字符串元组列表表示的线性顺序,将顺序输出为字符串列表

java - 拆分为多个字符

Python:匹配并替换每行开头的所有空格

jQuery:使用正则表达式匹配货币

python - 如何解决在 dbf 中插入记录的时间元组错误

java - 实现可导航图的优雅方式?