【问题标题】:Regex problems matching invalid json string匹配无效 json 字符串的正则表达式问题
【发布时间】: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字符串中使用正则表达式?

【问题讨论】:

  • 请考虑查看下面的答案并告知是否一切正常。

标签: python json regex


【解决方案1】:

首先,您需要将字符串变量命名为textinput 是内置的。

你可以使用

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")

请参阅 regex demoPython demo。输出:

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

【讨论】:

    猜你喜欢
    • 2015-11-16
    • 2016-07-31
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2020-05-06
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多