python - 匹配无效 json 字符串的正则表达式问题
问题描述
我有一个截断/无效的 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字符串一起使用?
解决方案
首先,您需要将字符串变量命名为text
,input
是内置的。
您可以使用
regex_pattern = r'localTransactions\\":{\\"id\\":\\"(.*?)\\",\\"sourceApplication'
并检索您需要使用的匹配项
regex_result = re.search(regex_pattern, text)
if regex_result:
print("We have a match!", regex_result.group(1), sep="\n")
else:
print("No match")
We have a match!
11111111-239e-4f86-9f5a-111111111111
推荐阅读
- java - 如何使用 Thymeleaf th:each 在 div 中打印列表对象,而不是
- r - 我正在尝试在乐队上运行马赛克,在这个阶段,当我应用光栅时,它给了我这个错误
- javascript - React 的 Framer Motion 页面转换 - 问题
- xamarin - Xamarin SkiaSharp 缩放裁剪画布
- spinnaker - 在大三角帆中创建阶段特定参数?
- python - 运行以下代码后 Python 代码没有响应:
- javascript - HTML按钮未调用该函数
- docker - 在 GCR 上运行多架构映像时执行格式错误
- c# - 我们如何从已使用 ILRepack 合并到单个 DLL 的类库项目中调用当前项目中的资源字典
- toit - 特定时间的深度睡眠