2012-04-19 82 views
1

我有这样的事情匹配重复组

{{ 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,如果这是相关的。

回答

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) 
+0

嗯,但如果我有超过两组参数,以desc的形式:“val”,如果我有我喜欢的20 – gosukiwi 2012-04-19 17:58:36

+0

我相应地编辑了答案。 – 2012-04-19 18:35:28

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]; 
    } 
} 
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); 

但我可能是错的。 )