Ayush Somani
Ayush Somani

Reputation: 156

python regex to get key value pair

var abcConfig={
"assetsPublicPath":"https://abcd.cloudfront.net/"
} 
var abcConfig1={
 "assetsPublicPath1":"https://abcd.cloudfront.net/1" 
}

I am looking for a regex which generates key value pair

[
abcConfig: {"assetsPublicPath": "https://abcd.cloudfront.net/"},
abcConfig1: {"assetsPublicPath1": "https://abcd.cloudfront.net/1"}
]

Upvotes: 0

Views: 40

Answers (1)

Byron
Byron

Reputation: 302

Using your sample, I came up with the following example code in Python:

import re
rs = r'var\s+(?P<key>.*)\s*=\s*(?P<val>\{\s*.*?\s*\})\s*'

m = re.finditer(rs, test)
for mm in m: 
    gd = mm.groupdict()
    print(gd['key'], gd['val'])

This captures the key and value from the text into named groups, which get stored in the groupdict. You could then use these values to build your dictionary or do whatever you need to do.

Upvotes: 1

Related Questions