[英]Regex to extract repeated sequence from string
I am trying to extract the function arguments from my string s
我正在尝试从字符串
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\'; }' ]
*/
It is only capturing c
. 它仅捕获
c
。
/*
[ 'function (a, b, c)',
'a',
'b',
'c',
index: 0,
input: 'function (a, b, c) { return \'hello\'; }' ]
*/
This code is used in a module and must be accomplished with a single regular expression . 此代码在模块中使用,并且必须使用单个正则表达式来完成。 Other techniques I've seen on StackOverflow will not work.
我在StackOverflow上看到的其他技术将不起作用。
You can't have a variable number of capturing groups within a regular expression. 正则表达式中不能有可变数量的捕获组。 The best you can probably do is:
您可能可以做的最好的事情是:
var s = "function (a, b, c) { return \'hello\'; }";
s.match(/.*?\((.*)\)/)[1].split(/[,\s]+/);
// returns ["a", "b", "c"]
I would suggest to divide the task to sub-tasks: 我建议将任务划分为子任务:
Like this: 像这样:
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.