Home > front end >  Regex matching key value pairs inside curly brackets
Regex matching key value pairs inside curly brackets

Time:03-02

I’m trying to capture key:value pairs inside curly brackets. For the following string it should return something like k2:v2 and k3:v3

Str = “k1:v1abc{k2:v2,k3:v3}{test}”

I have the following regexes which capture what I need individually, but I don’t know how to combine them together.

/(\w ):(\w )/g >>> Captures key:value /{.*?}/g >>> Captures everything between {}

CodePudding user response:

If the pair is only inside one set, then you can use split

const str = `k1:v1abc{k2:v2,k3:v3}{test}`
console.log(str.split("{")[1].split("}")[0].split(","))

CodePudding user response:

If your environment supports a quantifier in a lookbehind assertion:

(?<={[\w:,]*)\w :\w (?=[\w:,]*})

The pattern matches:

  • (?<={[\w:,]*) Positive lookbehind, assert { and optional repetitions of the allowed chars to the left
  • \w :\w Match 1 word chars : and 1 word chars
  • (?=[\w:,]*}) Positive lookahead, assert optional repetitions of the allowed chars to the right and }

See a regex demo.

const str = "k1:v1abc{k2:v2,k3:v3}{test}";
const regex = /(?<={[\w:,]*)\w :\w (?=[\w:,]*})/g;
console.log(str.match(regex));

Another way could be using 2 passes, first matching the format and get the part between the curly braces in a capture group.

If there is a match, split group 1 on a comma.

{(\w :\w (?:,\w :\w )*)}

The pattern matches:

  • { Match opening {
  • ( Capture group 1
    • \w :\w Match 1 word chars : and 1 word chars
    • (?:,\w :\w )* Optionally repeat a , and the same previous pattern
  • )
  • } Match closing }

const str = "k1:v1abc{k2:v2,k3:v3}{test}";
const regex = /{(\w :\w (?:,\w :\w )*)}/;
const m = str.match(regex);
if (m) console.log(m[1].split(","));

  • Related