简体   繁体   English

正则表达式从字符串中提取重复序列

[英]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\'; }' ]
*/

The problem 问题

It is only capturing c . 它仅捕获c

Desired output 所需的输出

/*
[ 'function (a, b,   c)',
  'a',
  'b',
  'c',
  index: 0,
  input: 'function (a, b,   c) { return \'hello\'; }' ]
*/

Disclaimer 免责声明

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: 我建议将任务划分为子任务:

  • Retrieve list of arguments 检索参数列表
  • Split retrieved list 分割检索列表
  • Compose the result 撰写结果

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));​

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM