首页 > 解决方案 > 匹配无效 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字符串一起使用?

标签: pythonjsonregex

解决方案


首先,您需要将字符串变量命名为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")

请参阅正则表达式演示Python 演示。输出:

We have a match!
11111111-239e-4f86-9f5a-111111111111

推荐阅读