gpt4 book ai didi

javascript - 正则表达式:立即捕获某些文本与左括号和右括号之间的单词

转载 作者:行者123 更新时间:2023-12-01 03:49:08 24 4
gpt4 key购买 nike

我并不是正则表达式方面的专家,尤其是困难的正则表达式。我想要位于括号之间和单词“index”之后的字符串。

"(NO3)  index(doc.id(), doc.description)  index (doc.id)" 

会返回

"[ 'doc.id(), doc.description' ,  'doc.id' ]"

到目前为止我做了什么 https://jsfiddle.net/asjbcvve/

最佳答案

匹配字符串内的括号会使这变得困难。递归正则表达式将匹配它,但并非所有正则表达式引擎都实现它。例如,JS 不会(PCRE 会)

带递归的正则表达式

这在 JS 和许多其他正则表达式引擎中不起作用

index\s*\((([^\(\)]*(\([^\(\)]*\g<2>\))?)*)

不带递归且带 1 个嵌套括号的正则表达式

index\s*\((([^\(\)]*(\([^\(\)]*\))?)*)

他们都在第一组中捕获了你想要的东西。

示例:

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<1> 替换为整个组 2 的文字即可。重复您期望在字符串中出现的嵌套括号的次数.

关于javascript - 正则表达式:立即捕获某些文本与左括号和右括号之间的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43363357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com