我正在尝试从字符串 s
中提取函数参数
var s = "function (a, b, c) { return \'hello\'; }";
var re = /^function[^\(]*\(\W*(?:(\w+)[,\s)]*)+\)/g;
console.log( re.exec(s) );
/*
[ 'function (a, b, c)',
'c',
index: 0,
input: 'function (a, b, c) { return \'hello\'; }' ]
*/
问题
它仅捕获c
。
期望的输出
/*
[ 'function (a, b, c)',
'a',
'b',
'c',
index: 0,
input: 'function (a, b, c) { return \'hello\'; }' ]
*/
免责声明
此代码在模块中使用,并且必须使用单个正则表达式来完成。 Other techniques我在 StackOverflow 上看到行不通。
最佳答案
在正则表达式中不能有可变数量的捕获组。你能做的最好的事情可能是:
var s = "function (a, b, c) { return \'hello\'; }";
s.match(/.*?\((.*)\)/)[1].split(/[,\s]+/);
// returns ["a", "b", "c"]
关于javascript - 正则表达式从字符串中提取重复序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12376312/