[英]Regular expression only matches full match and not group
I am using re.findall in python to match each line of a log file and extract the json data from that line. 我在python中使用re.findall来匹配日志文件的每一行,并从该行提取json数据。 Here is an example line: 这是示例行:
<134>1 2017-01-23T10:54:47.111-01:11 bla blabla - - <-- '{"jsondata": "1.0", "result": null, "id": 0}'
And the code I'm using on it: 我在上面使用的代码:
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)
That returns this (yes there are two): 返回这个(是的,有两个):
[('\'{"jsondata": "1.0", "result": null, "id": 0}\'', '"jsondata": "1.0", "result": null, "id": 0')]
But I need it to return just the json data from that line in json format : 但是我需要它以json格式仅从该行返回json数据:
{"jsonrpc": "2.0", "result": null, "id": 2530}
When I put my regex into regex101, 当我将正则表达式放入regex101中时,
\'\{(.*?)\}\'
I get a group match for 我参加了一场团体赛
"jsondata": "1.0", "result": null, "id": 0
and full match for 并完全匹配
'{"jsondata": "1.0", "result": null, "id": 0}'
So this tells me findall is returning the group. 因此,这告诉我findall正在返回小组。 How can I fix this to return the full match, the json object? 如何解决此问题以返回完全匹配的json对象?
Try using this regular expression: 尝试使用以下正则表达式:
r"({.*?})"
This should take all content within the "{ ... }"s 这应包含“ {...}”内的所有内容
log_line = 'sdgfjk fgkglhdfg <-- fdfsd dsdasds {"jsondata": "1.0", "result": null, "id": 0} dasdsad khfsldfg'
print(re.findall(r"({.*?})", log_line))
Here's my output: 这是我的输出:
['{"jsondata": "1.0", "result": null, "id": 0}']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.