【问题标题】:Python Regex for pattern matching用于模式匹配的 Python 正则表达式
【发布时间】:2016-06-15 18:38:20
【问题描述】:

我正在尝试解析示例输入 test_string1 如下:

import re
TEST_STRING1 = """Using definitions from (yyyy/mm/dd): 2016/6/8
The following files are collected:
  File: Test.exe
    Source: Google
    avping blob: 123123

Downloaded 3 Files
"""
def fun():

    regex_exp = re.compile(r"File:\s(?P<File>[^\n\r\t]+?)[\n\r\t\s]*?"
                           r"Source:\s(?P<Source>.*)[^\w\d]*?"
                           r"avping\sblob:\s(?P<Avping_blob>([A-F]|[a-f]|[0-9]){6})")
    result = {}
    result['Files'] = []
    for m in re.finditer(regex_exp, TEST_STRING1):
        result['Files'].append(m.groupdict())
    print result
if __name__ == "__main__":
    fun()

以上代码的输出是:

{'Files': [{'Source': 'Google', 'File': 'Test.exe', 'Avping_blob': '123123'}]}

我想让 Input 中的一些字段成为可选字段,例如 avping blob: 喜欢

TET_STRING1 = """Using definitions from (yyyy/mm/dd): 2016/6/8
The following files are collected:
  File: Test.exe
    Source: Google

Downloaded 3 Files
"""

在上面的那个 casa 正则表达式返回不匹配。

我已将正则表达式更新为

regex_exp = re.compile(r"(File:\s(?P<File>[^\n\r\t]+?)[\n\r\t\s]*?"
                           r"Source:\s(?P<Source>.*)[^\w\d]*?"
                           r"|avping\sblob:\s(?P<Avping_blob>([A-F]|[a-f]|[0-9]){6}))")

在最后一行之前添加|。但随后它给出了 2 个匹配 OR 作为

{'Files': [{'Source': 'Google', 'File': 'Test.exe', 'Avping_blob': None}, {'Source': None, 'File': None, 'Avping_blob': '123123'}]}

我应该如何编写匹配两种输入类型(有和没有可选字段)的模式的正则表达式? 谢谢

【问题讨论】:

    标签: python regex pattern-matching


    【解决方案1】:

    您可以使用可选的非捕获组并使用[^\w\d]* 贪婪版本:

    (File:\s(?P<File>[^\n\r\t]+?)[\n\r\t\s]*?Source:\s(?P<Source>.*)[^\w\d]*(?:avping\sblob:\s(?P<Avping_blob>[A-Fa-f0-9]{6}))?)
    

    regex demo

    在您的代码中:

    regex_exp = re.compile(r"(File:\s(?P<File>[^\n\r\t]+?)[\n\r\t\s]*?"
                           r"Source:\s(?P<Source>.*)[^\w\d]*"    # <- Here ? is removed
                           r"(?:avping\sblob:\s(?P<Avping_blob>[A-Fa-f0-9]{6}))?)")
                             ^^^                                               ^
    

    另外,([A-F]|[a-f]|[0-9]){6}) = (?P&lt;Avping_blob&gt;[A-Fa-f0-9]{6})

    【讨论】:

    • 感谢您的回答:我得到的结果为 '{'Files': [{'Source': 'Google', 'File': 'Test.exe', 'Avping_blob': None} ]}' 在 python 代码中的两种情况下。 avping_blob 在这两种情况下都是 NONE
    • 试用更新版本。那么,第二个可以是 NONE,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多