1

我正在尝试从我的字符串中提取函数参数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\'; }' ]
*/

免责声明

此代码在模块中使用,并且必须使用单个正则表达式来完成。我在 StackOverflow 上看到的其他技术将不起作用。

4

2 回答 2

1

您不能在正则表达式中拥有可变数量的捕获组。您可能做的最好的事情是:

var s = "function (a, b,   c) { return \'hello\'; }";
s.match(/.*?\((.*)\)/)[1].split(/[,\s]+/);

// returns ["a", "b", "c"]
于 2012-09-11T19:25:34.630 回答
0

我建议将任务划分为子任务:

  • 检索参数列表
  • 拆分检索到的列表
  • 编写结果

像这样:

var reFuncDecl = /^function\s*\(([^)]+)\)/g,
    reSplitArg = /[,\s]+/;

function funcInfo(s) {
    var matches = reFuncDecl.exec(s),
    args = matches[1].split(reSplitArg);
    reFuncDecl.lastIndex = 0;
    return {
        declaration: matches[0],
        args: args,
        input: s
    };
}


var s = "function (a, b,   c,d,e,\nf) { return \'hello\'; }",
    info = funcInfo(s);
for(var prop in info) {
    document.write(prop + ': ' + info[prop] + '<br />');
}
console.log(funcInfo(s));​

演示

于 2012-09-11T20:04:55.493 回答