1
var q = '{[{main}(other data)][{data}(other data)][{address}(other data)]}';

var qm = q.match(/\[(.*?)\]/g);  

console.log(qm);

The above regex returns text that's between parenthesis.

Eg:

 [{data}(other data)]

How can the above Regex be rewritten so I supplied a string like 'data' it would return [{data}(other data)]. i.e the part with parenthesis that contains the string in curly braces.

jmenezes
  • 1,888
  • 6
  • 28
  • 44

2 Answers2

1

Matches string inside the curly brace

\[{data}\(.*?*\)\]

Regex Demo

var q = '{[{main}(other data)][{data}(other data)][{address}(other data)]}';

var qm = (str) => q.match(new RegExp(`\\[{${str}}\\(.*?\\)\\]`, 'g'));

console.log(qm('data'));

Matches string inside the curly brace and parenthesis

\[{data}\(.*?data[^)]*\)\]

Regex Demo

var q = '{[{main}(other data)][{data}(other data)][{address}(other data)]}';

var qm = (str) => q.match(new RegExp(`\\[{${str}}\\(.*?${str}[^)]*\\)\\]`, 'g'));

console.log(qm('data'));
User863
  • 19,346
  • 2
  • 17
  • 41
  • What is the `${str}` in your code? Is it a Regex Literal or Template Literal. Do older version of IE support this? – jmenezes Jun 29 '20 at 15:27
  • @jmenezes Its a template literal. For browser support, you can concat as normal string – User863 Jun 29 '20 at 16:03
  • I'm using your first code snippet. Any idea how I can get the results without the `[` `]` in the result. So instead of `[{data}(other data)]` it'll be `{data}(other data)` (no square brackets). If it's possible i'll post another question. – jmenezes Jun 30 '20 at 15:38
0

Using your qm variable, you can iterate over the matches and test for the string between the first curly braces like so:

var q = '{[{main}(other data)][{data}(other data)][{address}(other data)]}';
var qm = q.match(/\[(.*?)\]/g);

for (let e of qm)
  if (e.match('\{([^\)]+)\}')[1] == "data")
    console.log(e);
Al.G.
  • 4,327
  • 6
  • 31
  • 56