2012-04-19 7 views
1

私はa_name、すべての説明と値を一致させたいこのマッチング繰り返しグループ

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

のようなものを持っています。

regex I'm using rightは今

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

あるしかし、唯一の最後のグループと一致していることを、どのように私はすべてのグループが一致することができますか? 関連性のあるJavaScriptを使用しています。 JavaScriptで

答えて

0

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

ummmしかし、desc: "val"という形式のパラメータ群が3つ以上ある場合、どうすれば20のようになりますか – gosukiwi

+0

私はそれに応じて答えを編集しました。 –

0

あなたが名前と、その後の説明/値のペアを取得する最初の、2つの部分でこれを行う必要があるでしょう。

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:あなたは1つの正規表現でそれを行うことができますが、それは物事を複雑にしない:あなたが最初の抽出:

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

しかし、私は間違っている可能性があります。 )

関連する問題