r = """(?x) { (\w+) : ( (?: [^{}] | {.+?} )+ ) } """ z = "{1:xxxx}{2:xxxx}{3:{10:xxxx}}{4:'xxxx'}" print dict(re.findall(r, z)) # {'1': 'xxxx', '3': '{10:xxxx}', '2': 'xxxx', '4': "'xxxx'"}
Feel free to convert to a single line file, if you want - just remove (?x) and all spaces from the regular expression.
The above analysis of only one level of nesting, for processing arbitrary depth, considers a more advanced regex module that supports recursive templates:
import regex r = """(?x) { (\w+) : ( (?: [^{}] | (?R) )+ ) } """ z = "{1:abc}{2:{3:{4:foo}}}{5:bar}" print dict(regex.findall(r, z))
georg source share