Home > Mobile >  Regex expression to get data in this format
Regex expression to get data in this format

Time:02-04

I have the following strings:

'foo(123abc)bar(456def)'
// or
'foo(123abc) bar(456def)'

I need the JavaScript code to get the word that is to the left of the parentheses and the content that is inside them: (either of the two ways)

['foo', '123abc', 'bar', '456def']
// or
{
  'foo': '123abc',
  'bar': '456def'
}

I tried /\w\(([^\)]*)\)/.exec('foo(123abc)bar(456def)'), but the result was ['o(123abc)', '123abc']

I don't know much about regex!

CodePudding user response:

You can achieve that by replacing one of the parantheses with the other and then splitting the string by the remaining parantheses:

let result1 = 'foo(123abc)bar(456def)'.replaceAll(')', '(').split('(');

and you can apply a regex as well if you need to do so:

let result2 = 'foo(123abc)bar(456def)'.split(/(|)/);

In both cases you will have an empty string as the last element, so you will need to call result1.splice(-1, 1) or result2.splice(-1, 1) respectively.

CodePudding user response:

The next provided example implements a validating but somewhat forgiving regex based parsing approach. The regex makes use of named groups in order to capture (and subsequently process easier) each (loosely) syntactically correct key-value pair.

The pattern is as follows ... /(?<key>\w )\s*\((?<value>[^()] ) \s*\)/g.

The end result gets aggregated/reduced from an array of matching regex-results.

function extractKeyValuePairs(data) {
  const regXKeyValue =
    // see...[https://regex101.com/r/zjcjdu/1]
    /(?<key>\w )\s*\((?<value>[^()] ) \s*\)/g;

  return [
    ...String(data)
      .matchAll(regXKeyValue)
  ]
  .reduce((result, { groups: { key, value } }) =>
    Object.assign(result, { [key]: value.trim() }), {}
  );
}

const sampleData = `foo (123abc) bar( "456def"  , baz( foo )
biz( "bar" ),buz ('123abc' )boz("456def)`;

console.log({
  result: extractKeyValuePairs(sampleData),
  sampleData,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }

  •  Tags:  
  • Related