【发布时间】:2021-07-10 07:06:25
【问题描述】:
我有一个截断/无效的 json 字符串,我需要从中提取 GUIID。但是我无法在我的正则表达式匹配中使用双引号。
import re
input = '{\\"event\\":{\\"header\\":{\\"transactions\\":{\\"localTransactions\\":{\\"id\\":\\"11111111-239e-4f86-9f5a-111111111111\\",\\"sourceApplication\\":{\\"name\\":\\"worker\\",\\"host\\":\\"worker-67bcdfc6bb\\"},\\"createdAt\\":\\"2021-04-08T14:05:03.571Z\\",\\"websocketId\\":\\"abc=\\"},\\"localTransaction\\":[]},\\"user\\":null,\\"interceptorId\\":null},\\"payload\\":{\\"operation\\":{\\"operationCode\\":\\"500\\",\\"applicationErrorCode\\":\\"202\\",\\"operationMessage\\":\\"Exception\\",\\"status\\":\\"failure\\",\\"reason\\":\\"Failure - Failed to ggg.\\"},\\"response\\":{\\"operation\\":{\\"operationCode\\":\\"500\\",\\"applicationErrorCode\\":\\"CP0202\\",\\"operationMessage\\":\\"Exceptio. We are working on it and will in [TRUNCATED]'
regex_pattern = '(?<=localTransactions)(.*)(?=sourceApplication)' #This works but it is not ideal
regex_result = re.search(regex_pattern, input)
if regex_result:
print("We have a match!")
print(regex_result.group())
else:
print("No match")
此代码导致以下匹配:\":{\"id\":\"11111111-239e-4f86-9f5a-111111111111\",\"
但我真正想要的只是 guid 值,11111111-239e-4f86-9f5a-111111111111 所以我一直在尝试各种正则表达式模式,例如:
regex_pattern = '(?<=localTransactions\\":{\\")(.*)(?=\\",\\"sourceApplication)'
但是使用它什么也找不到。
如何在双引号/json字符串中使用正则表达式?
【问题讨论】:
-
请考虑查看下面的答案并告知是否一切正常。