首页 > 解决方案 > 提取python字符串中给定键的值

问题描述

'2019-01-04T03:22:17.950795+00:00 CONSOLE:0 (null) - 01-04-2019 03:22:17.950 INFO (SGUI.APP) - report_event:{"event":"pip-started", "time":"110ms"}#012'

由此,我的目标是使用“事件”和“时间”作为识别价值的关键来提取“点子开始”和“110”

标签: pythonregex

解决方案


此表达式可能会提取这些值:

import re

regex = r"\"event\":\"([^\"]+)\"|\"time\":\"(\d+)"
test_str = "2019-01-04T03:22:17.950795+00:00 CONSOLE:0 (null) - 01-04-2019 03:22:17.950 INFO (SGUI.APP) - report_event:{\"event\":\"pip-started\", \"time\":\"110ms\"}#012"

print(re.findall(regex, test_str))

输出

[('pip-started', ''), ('', '110')]

该表达式在regex101.com的右上角面板上进行了说明,如果您希望探索/简化/修改它,并且在此链接中,您可以查看它如何与一些示例输入匹配,如果您愿意的话。


推荐阅读