Regex problems matching invalid json string

Viewed 56

I have a truncated/invalid json string that I need to extract a GUIID from. However I am unable to use double quotes in my regex match.

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

This code results in the following match: \":{\"id\":\"11111111-239e-4f86-9f5a-111111111111\",\"

But what I actually want is only the guid value, 11111111-239e-4f86-9f5a-111111111111 So I have been experimenting with various regex patterns such as this:

 regex_pattern = '(?<=localTransactions\\":{\\")(.*)(?=\\",\\"sourceApplication)'

But using this finds nothing at all.

How to use regex with double quotes/json strings?

1 Answers

First, you need to name the string variable as something like text, input is a built-in.

You can use

regex_pattern = r'localTransactions\\":{\\"id\\":\\"(.*?)\\",\\"sourceApplication'

and retrieve the match you need using

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

See the regex demo and the Python demo. Output:

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