【问题标题】:Why my code not working in return value for Python Regex为什么我的代码在 Python 正则表达式的返回值中不起作用
【发布时间】:2019-10-31 10:16:25
【问题描述】:

我编写了一个程序来查找匹配项。它工作正常。如果字符串不正确,则必须返回 false。例如,如果我的 string_ 包含 2 个逗号,或者如果出现其他字符串而不是拒绝或任何其他字符串,则它必须返回 false。我的字符串只期望字符串为拒绝或任何

import re
string_ = '''192.168.1.1,192.168.1.2/32,192.168.1.5-192.168.1.7,reject,any,
reject,192.168.1.1/32,reject,any,
172.168.1.4-172.168.1.4,reject'''
result = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/?\d{0,}|[any|reject]+', string_)
#print(result)
if result :
    print (True)

期望下面的字符串为假

    test = '''192.168.1.1,192.168.1.2/32,192.168.1.5-192.168.1.7,reject,any,ip_address
reject,192.168.1.1/32,reject,any,
172.168.1.4-172.168.1.4,reject'''
bool(re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/?\d{0,}|[any|reject]+', test))

预期的结果是假的,我的结果是真的

test1 = '''192.168.1.1,192.168.1.2/32,192.168.1.5-192.168.1.7,reject,any,,,,
    reject,192.168.1.1/32,reject,any,
    172.168.1.4-172.168.1.4,reject'''
bool(re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/?\d{0,}|[any|reject]+', test1))

预期的结果是假的,我的结果是真的

预期结果

False

【问题讨论】:

  • 你为什么会期待False?您的正则表达式有很多问题,您根本不检查逗号,您的 [any|reject]+ 将接受例如aaa...
  • 为什么你认为它是假的?您可能想在在线解析器中调试或编写您的正则表达式以查看它的作用。这是您的测试数据和正则表达式,您可以看到与您当前的正则表达式有很多匹配 regex101.com/r/GOHNWM/1
  • 请查看this solution,是您需要的吗?这是生成的regex demo
  • @Wiktor Stribiżew 它的完美工作,有没有办法将它作为一个正则表达式传递
  • 在下面查看我的答案。

标签: python regex


【解决方案1】:

你可以使用

^(?:\d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?(?:-\d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?)?|reject|any)(?:\s*,\s*(?:\d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?(?:-\d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?)?|reject|any))*$

由于正则表达式由块组成,因此更容易在代码中动态构建:

import re
string_ = '''192.168.1.1,192.168.1.2/32,192.168.1.5-192.168.1.7,reject,any,ip_address
reject,192.168.1.1/32,reject,any,
172.168.1.4-172.168.1.4,reject'''
ip_rx = r'\d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?'
# More precise:
# ip_rx = r'(?: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}'
block=r"(?:{0}(?:-{0})?|reject|any)".format(ip_rx)
print(bool(re.search(r'^{0}(?:\s*,\s*{0})*$'.format(block), string_))) # => False

Python demo

详情

  • ^{0}(?:\s*,\s*{0})*$ - 匹配完全匹配 block 模式的字符串,该模式后跟 0 次或多次出现的 ,block 模式
  • (?:{0}(?:-{0})?|reject|any) 是匹配ip 模式的(?:{0}(?:-{0})?|reject|any) 模式,可以选择跟随-ip 模式或rejectany 子字符串
  • \d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?ip 模式,可以改进为仅匹配有效 IP,(?: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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-01
    • 2012-11-17
    • 1970-01-01
    • 2022-01-20
    • 2012-11-17
    • 1970-01-01
    • 2013-02-02
    相关资源
    最近更新 更多