Javascript 匹配重复组
我有类似的东西Javascript 匹配重复组,javascript,regex,Javascript,Regex,我有类似的东西 {{ a_name a_description:"a value" another_description: "another_value" }} 我想匹配一个_名称以及所有描述和值 现在的问题是 但这只匹配最后一组,我如何匹配所有组? 如果相关的话,我正在使用JavaScript。在JavaScript中: var re = /{{ (\w+) (\w+):\"([a-zA-Z_ ]+)\" (\w+): \"([a-zA-Z_ ]+)\" }}/ var out = re.
{{ a_name a_description:"a value" another_description: "another_value" }}
我想匹配一个_名称以及所有描述和值
现在的问题是
但这只匹配最后一组,我如何匹配所有组?
如果相关的话,我正在使用JavaScript。在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" }}')
输出将是一个包含所需匹配项的数组
如果需要捕获一般数量的键:值对,这将有助于:
var str = '{{ a_name a_description: "a value" another_description: "another_value" }}'
var pat = /[a-zA-Z_]+: "[a-zA-Z_ ]*"/gi
str.match(pat)
您必须分两部分完成此操作,首先获取名称,然后获取描述/值对
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];
}
}
我真的认为解决这个问题的正确方法是瀑布式方法:首先提取函数名,然后使用split解析参数
但我可能错了 嗯,但是如果我有两组以上的参数,以desc:val的形式,如果我有20个呢
re = /(?:{{\s*([^ ]+) )|(?:(\w+):\s*"([^"]+)"\s*)+?/g;
while ((res = re.exec(str)) !=null) {
if (!name) {
name = res[1];
}
else {
description = res[2];
value = res[3];
}
}
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);