JavaScript Regex查找与特定起始和结束模式匹配的所有子字符串



我想要一个Javascript正则表达式或任何可能的解决方案,对于给定的字符串,查找以特定字符串开头、以特定字符结尾的所有子字符串。返回的子字符串集可以是一个数组。

这个字符串也可以嵌套在括号中。

var str = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))";

起始字符=";myfunc";结束字符="(&"。这里的结尾字符应该是第一个匹配的结束符。

output:带参数的函数。

[myfunc(1,2),
myfunc(3,4),
myfunc(5,6),
func(7,8)]

我试过这个。但是,它总是返回null。

var str = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))";
var re = /myfunc.*?)/ig
var match;
while ((match = re.exec(str)) != null){
console.log(match);
}

你能在这里帮忙吗?

我测试了您的正则表达式,它似乎运行良好:

let input = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))"
let pattern = /myfunc.*?)/ig 
// there is no need to use m since it does nothing, and NO you dont need it even if you use 'm' at the beginning.
console.log(input.match(pattern)) 
//[ "myfunc(1,2)", "myfunc(3,4)", "myfunc(5,6)" ]

如果您使用(?:my|)func(.+?),您也可以捕获"func(7,8("。

(?:my|)
(    start of group
?:   non capturing group
my|  matches either 'my' or null, this will match either myfunc or func
)    end of group

在此处测试正则表达式:https://regex101.com/r/3ujbdA/1

最新更新