我真的不是正则表达式的专家,尤其是硬盘。 我希望字符串位于括号之间和字后面#34; index"
"(NO3) index(doc.id(), doc.description) index (doc.id)"
将返回
"[ 'doc.id(), doc.description' , 'doc.id' ]"
到目前为止我做了什么 https://jsfiddle.net/asjbcvve/
答案 0 :(得分:2)
匹配字符串中的括号可以使这很难。递归正则表达式将匹配,但并非所有正则表达式引擎都实现它。例如JS没有(PCRE确实)
带有递归的这在JS和许多其他正则表达式引擎中不起作用
index\s*\((([^\(\)]*(\([^\(\)]*\g<2>\))?)*)
index\s*\((([^\(\)]*(\([^\(\)]*\))?)*)
他们都能在第1组中找到你想要的东西。
var rx = /index\s*\((([^\(\)]*(\([^\(\)]*\))?)*)/g; //works with 1 nested parentheses
var rx_recursion = /index\s*\((([^\(\)]*(\([^\(\)]*\g<2>\))?)*)/g; //works with any number of nested parentheses, but JS regex engine doesn't suppoorts recursion
var res = [], m;
var s = "(NO3) index(doc.id(s)(), doc.description) index (doc.id) index(nestet.doesnt.work((())))";
while ((m=rx.exec(s)) !== null) {
res.push(m[1]);
}
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";
index\s* - Match literal 'index' followed by any number of white characters
\( - Match literal openning parenthesis character
( - Group 1
( - Group 2
[^\(\)]* - Match anything that is not parentheses
( - Group 3
\( - Match literal opening parenthesis
[^\(\)]* - Match anything that is not parentheses
\g<1> - Recursively match group 1
\) - Match literal closing parenthesis
)? - End group 3, match it one or more times
)* - End group 2, match it zero or more times
) - End group 1
如果您需要匹配多个嵌套括号,但您选择的引擎不支持递归,只需替换\ g&lt; 1&gt;使用整个组的字面值2.重复与预期在字符串中出现的嵌套括号一样多的次数。