匹配重复的组

时间:2012-04-19 17:01:51

标签: javascript regex

我有类似的东西

{{ a_name a_description:"a value" another_description: "another_value" }}

我希望匹配a_name以及所有描述和值。

regex I'm using right现在是

{{\s*(?<function>\w+)\s+((?<attr>\w+)\s*\:\s*\"(?<val>\w+?)\"\s*)+}}

但这只匹配最后一组,我如何匹配所有组? 如果相关,我正在使用JavaScript。

3 个答案:

答案 0 :(得分:0)

在JavaScript中:

var re = /{{ (\w+) (\w+):\"([a-zA-Z_ ]+)\" (\w+): \"([a-zA-Z_ ]+)\" }}/
var out = re.exec('{{ a_name a_description:"a value" another_description: "another_value" }}')

out将是一个包含您需要的匹配项的数组。

如果您需要捕获通用数量的key: "value"对,这将有所帮助:

var str = '{{ a_name a_description: "a value" another_description: "another_value" }}'
var pat = /[a-zA-Z_]+: "[a-zA-Z_ ]*"/gi
str.match(pat)

答案 1 :(得分:0)

您必须分为两部分,首先获取名称,然后获取描述/值对。

str = '{{ a_name a_description:"a value" another_description: "another_value" }}';
name = /\w+/.exec(str);

// notice the '?' at the end to make it non-greedy.
re = /(?:(\w+):\s*"([^"]+)"\s*)+?/g;
var res;
while ((res = re.exec(str)) !=null) {
    // For each iteration, description = res[1]; value = res[2];
}

ETA :您可以使用一个正则表达式执行此操作,但确实会使事情变得复杂:

re = /(?:{{\s*([^ ]+) )|(?:(\w+):\s*"([^"]+)"\s*)+?/g;
while ((res = re.exec(str)) !=null) {
    if (!name) {
        name = res[1];
    }
    else {
        description = res[2];
        value = res[3];
    }
}

答案 2 :(得分:0)

我认为采用这种情况的正确方法是瀑布式方法:首先提取函数名称,然后使用split解析参数。

var testString = '{{ a_name a_description:"a value" another_description: "another_value" }}';
var parser = /(\w+)\s*([^}]+)/;
var parts  = parser.exec(testString);

console.log('Function name: %s', parts[1]);
var rawParams = parts[2].split(/\s(?=\w+:)/);
var params    = {};
for (var i = 0, l = rawParams.length; i < l; ++i) {
  var t = rawParams[i].split(/:/);
  t[1] = t[1].replace(/^\s+|"|\s+$/g, ''); // trimming
  params[t[0]] = t[1];
}
console.log(params);

但我可能错了。 )