【发布时间】: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