2017-02-03 161 views
0

我在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對象?

回答

1

嘗試使用正則表達式:

r"({.*?})" 

這應該採取 「{...}」 S

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}'] 
+0

這精美地工作。我可以通過訪問list元素來訪問json數據。謝謝! –