【问题标题】:Regex fails to correctly parse IPv4 inputs [duplicate]正则表达式无法正确解析 IPv4 输入 [重复]
【发布时间】:2020-08-18 07:21:02
【问题描述】:

我正在尝试在 Python 中构建 IPv4 正则表达式。这就是我所拥有的:

r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'

这些是它错误分类的输入:

Input: "172.316.254.1"
Output: true
Expected Output: false

Input: "1.1.1.1a"
Output: true
Expected Output: false

Input: "1.23.256.255."
Output: true
Expected Output: false

Input: "64.233.161.00"
Output: true
Expected Output: false

Input: "64.00.161.131"
Output: true
Expected Output: false

Input: "01.233.161.131"
Output: true
Expected Output: false

Input: "1.1.1.1.1"
Output: true
Expected Output: false

Input: "1.256.1.1"
Output: true
Expected Output: false

Input: "1.256.1.1"
Output: true
Expected Output: false

Input: "255.255.255.255abcdekjhf"
Output: true
Expected Output: false

这是我拥有的代码。它基本上返回一个布尔值:

import re

def isIPv4Address(inputString):
    pattern = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
    
    return pattern.match(inputString) is not None

【问题讨论】:

    标签: python regex ipv4


    【解决方案1】:

    失败的测试似乎有两个原因:

    1. 匹配字符串的第一部分。
    2. 不检查数字格式和值。

    匹配字符串的第一部分

    以下测试失败,因为字符串的第一部分 (1.1.1.1) 与您的正则表达式匹配。额外的a 不会改变这一点:

    Input: "1.1.1.1a"
    Output: true
    Expected Output: false
    

    这是因为match 在字符串的第一部分匹配时返回一个对象。来自docs

    如果字符串开头的零个或多个字符与此匹配 正则表达式,返回对应的匹配对象。

    如果您只想要一个对象,则 whole 字符串匹配时,请使用 fullmatch。来自docs

    如果整个字符串匹配这个正则表达式,返回一个 对应的匹配对象。如果字符串不匹配,则返回 None 图案;请注意,这与零长度匹配不同。

    或者,您可以将$ 附加到原始正则表达式以匹配行/字符串的结尾。例如,r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'

    数字格式和数值

    以下测试失败,因为您的正则表达式未检查数字的格式或值。 \d{1,3} 只检查是否有 1 到 3 位数字。这匹配从 000 到 0 到 9 到 999 的所有值。

    Input: "01.233.161.131"
    Output: true
    Expected Output: false
    

    可以使用正则表达式检查值是否在 0 和 255 之间,但需要显着扩展当前的正则表达式。以this answer 为例。

    【讨论】:

    • 不幸的是它并没有解决问题。
    • 你试过什么?结果如何?不管怎样,我都更新了答案。
    • 我使用了fullmatch() 而不是match()。同样的问题。我还附加了$。也没有工作。
    • 请查看本页顶部的链接:您的问题之前已得到解答。 :)
    • 首先,这些答案要么对第 3 方库很重要,我无法在代码练习网络应用程序上执行此操作,要么它们在建议您的建议。
    猜你喜欢
    • 2014-02-05
    • 2019-08-29
    • 2022-10-14
    • 2011-01-23
    • 2012-11-21
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多