Home > Enterprise >  Regex get key value for string object like { key=value, .... }
Regex get key value for string object like { key=value, .... }

Time:11-02

I have string like

"{format=svg, width=383, height=480, transform=[40, 40, 40, 40], scaleX=1, scaleY=1}"

How can I return object with key value with regex like. Many thanks!

{
  format: 'svg',
  width: 383,
  height: 480,
  transform: [40, 40, 40, 40],
  scaleX: 1,
  scaleY: 1
}

CodePudding user response:

Here is a solution making several assumptions, which might differ from your needs:

  • keys are assumed to be alpha chars only
  • values that have a number pattern are assumed to be numbers
  • values that start and end with [ and ], respectively, are assumed to be a array containing numbers

const str = "{format=svg, width=383, height=480, transform=[40, 40, 40, 40], scaleX=1, scaleY=1}";
const regex = /([a-zA-Z] )=(\[[^\]]*]|.*?)[,\}]/g;
let obj = {};
str.replace(regex, function(m, key, val) {
  if(/^-?\d (\.\d )?$/.test(val)) {
    val = Number(val);
  } else if(/^\[.*\]$/.test(val)) {
    val = val
      .replace(/^\[(.*)\]$/, '$1')  // get rid of `[` and `]`
      .split(/, */)                 // split on comma and optional space
      .map(num => Number(num));     // convert each item to a number
  }
  obj[key] = val;
  return '';
});
console.log(obj);

Output:

{
  "format": "svg",
  "width": 383,
  "height": 480,
  "transform": [
    40,
    40,
    40,
    40
  ],
  "scaleX": 1,
  "scaleY": 1
}

Explanation of regex:

  • ([a-zA-Z] ) -- capture group one for key
  • = -- literal = sign
  • ( -- start of capture group 2 for value
  • \[[^\]]*] -- pattern representing an array of form [...]
  • | -- logical OR
  • .*? -- non-greedy scan
  • ) -- end of capture group 2 for value
  • [,\}] -- expect a comma or a curly bracket
  • Related