簡體   English   中英

正則表達式僅匹配完全匹配而不匹配組

[英]Regular expression only matches full match and not group

我在python中使用re.findall來匹配日志文件的每一行,並從該行提取json數據。 這是示例行:

<134>1 2017-01-23T10:54:47.111-01:11 bla blabla  - -  <-- '{"jsondata": "1.0", "result": null, "id": 0}'

我在上面使用的代碼:

 for line in jsonlog:
        json_marker = "<-- '{"
        if json_marker in line:
            #Extract whats between the single quotes on lines where a json is present
            x = re.findall(r"(\'\{(.*?)\}\')", line)

返回這個(是的,有兩個):

[('\'{"jsondata": "1.0", "result": null, "id": 0}\'', '"jsondata": "1.0", "result": null, "id": 0')]

但是我需要它以json格式僅從該行返回json數據:

{"jsonrpc": "2.0", "result": null, "id": 2530}

當我將正則表達式放入regex101中時,

\'\{(.*?)\}\' 

我參加了一場團體賽

"jsondata": "1.0", "result": null, "id": 0

並完全匹配

'{"jsondata": "1.0", "result": null, "id": 0}'

因此,這告訴我findall正在返回小組。 如何解決此問題以返回完全匹配的json對象?

嘗試使用以下正則表達式:

r"({.*?})"

這應包含“ {...}”內的所有內容

log_line = 'sdgfjk fgkglhdfg <-- fdfsd dsdasds {"jsondata": "1.0", "result":  null, "id": 0} dasdsad khfsldfg'

print(re.findall(r"({.*?})", log_line))

這是我的輸出:

['{"jsondata": "1.0", "result": null, "id": 0}']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM