【发布时间】:2021-06-09 02:47:33
【问题描述】:
我写了一个匹配字符串中所有函数名的正则表达式
Regex :- /([a-zA-Z ]*(?=\())/g
String:- (( MAX(1,2,3,4), min(1,2,3), max(3,4,5)))
上面的正则表达式通过检查后面跟“(”的一堆单词来匹配所有函数名。在这种情况下,匹配是MAX、MIN、 MAX(除了我使用 match.filter(String) 过滤的一些空字符串。)
在我的一种情况下,我只需要“FIRST”匹配函数及其 START 和 STOP 索引。 所以,我写了下面的函数来获取它。
var re = /([a-zA-Z ]*(?=\())/g;
var str = "max(1,2), min(1,2)";
while ((match = re.exec(str)) !== null) {
console.log("match found at " + match.index);
// Pick the first matching index from here ?
}
但这会进入一个无限循环并且它没有给出所需的输出(我确定上面的函数有问题,但不太确定是什么)。
Example string2 = (((( max(34234,234234,344) min(1,2,3)))))*23 + max(23434, 234234,234234))) - I only need the first matching function "max" from here along with it's start and stop index's.
【问题讨论】:
-
考虑在这里使用解析器而不是正则表达式。
-
括号内的文字索引有什么用?如果你只是想提取函数名和函数参数,你可以使用这个正则表达式:
/([a-zA-Z]+) *\(([^\)]*)\)/g -
@PeterThoeny 我只是想提取函数名称。我不需要参数列表。 (输出应该只是函数名 - 最大值、最小值及其起始字符位置和结束位置。
标签: javascript regex regex-group