Home > Mobile >  Regex to find variables inside curly braces of a Python JSON string
Regex to find variables inside curly braces of a Python JSON string

Time:12-02

So I'm trying to extract variables from a python json string.

Input:
sample_string = '{{"some_key_1":"{var1}",
                   "some_key_2":"Hello this is {var2} from {var3}"
                  }}'

expected_output = ["var1","var2","var3]

I have tried searching for the same and have come across the following regex patterns.

1.re.findall(r"{(.*?)}", sample_string)
2.re.findall(r"{(. ?)}", sample_string)

However the output that I get is :

current_output = ['"some_key_1":"{var1','var2','var3']

Note: The reason why sample_string has two curly braces at start and end is because I am going to use string.format() on the same at a later stage to replace variables.

How do I get the expected output as shown above?

CodePudding user response:

use [^{}] that means no bracket chars

sample_string = '{{"s_1":"{var1}"," some_key_2": "Hello this is {var2} from {var3}"}}'
print(re.findall(r"{([^{}]*?)}", sample_string))  # ['var1', 'var2', 'var3']
  • Related