提取python中字符串内给定键的值

时间:2019-07-20 04:00:56

标签: python regex

'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'

由此,我的目标是使用“事件”和“时间”作为识别值的键来提取“ pip-started”和“ 110”

2 个答案:

答案 0 :(得分:0)

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

const days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"],
    opening_hours={"0":{close:"17:00:00",is_open:true,open:"09:00:00"},"1":{close:"17:00:00",is_open:true,open:"09:00:00"},"2":{close:"17:00:00",is_open:true,open:"09:00:00"},"3":{close:"17:00:00",is_open:true,open:"09:00:00"},"4":{close:"17:00:00",is_open:true,open:"09:00:00"},"5":{is_open:false},"6":{is_open:false}},
    updatedEntries = Object.entries(opening_hours).map(([k, v]) => [days[k], v]),
    output = Object.fromEntries(updatedEntries);

console.log(output)

输出

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))

该表达式在regex101.com的右上角进行了解释,如果您想探索/简化/修改它,在this link中,您可以观察到它如何与某些示例输入匹配,如果你喜欢。

答案 1 :(得分:0)

import re
import json

string = '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'

extract = re.findall(r'\{.*\}', string)

json.loads(extract[0]).get('event')
json.loads(extract[0]).get('time')

输出:

 'pip-started'
 '110ms'

json.loads可用于从字符串创建字典。有了字典后,请使用get获取值。