简体   繁体   English

正则表达式匹配方括号内大括号内的字符串

[英]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)] .如何重写上面的正则表达式,所以我提供了一个类似'data'的字符串,它将返回[{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:使用您的qm变量,您可以遍历匹配项并测试第一个花括号之间的字符串,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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