简体   繁体   中英

Regex to match string inside curly braces inside square brackets

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)] . ie the part with parenthesis that contains the string in curly braces.

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'));

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM