2009-05-09 30 views
60

g修飾子が設定されているとJavascriptのサブマッチが機能しなくなるのはなぜですか?JavaScript正規表現とサブマッチ

var text = 'test test test test'; 

var result = text.match(/t(e)(s)t/); 
// Result: ["test", "e", "s"] 

上記作品罰金、result[1]"e"あるとresult[2]"s"です。

var result = text.match(/t(e)(s)t/g); 
// Result: ["test", "test", "test", "test"] 

上記のキャプチャグループは無視されます。次は唯一の有効なソリューションですか?グローバル修飾子が設定されている場合、あなたが見つけたとしてStringmatch()機能を使用して

var result = text.match(/test/g); 
for (var i in result) { 
    console.log(result[i].match(/t(e)(s)t/)); 
} 
/* Result: 
["test", "e", "s"] 
["test", "e", "s"] 
["test", "e", "s"] 
["test", "e", "s"] 
*/ 

答えて

91

は、グループを捕獲戻りません。

この場合、RegExpオブジェクトを使用し、そのexec()関数を呼び出すとします。 Stringmatch()は、これらの場合を除き、RegExpexec()機能とほぼ同じです。グローバルモディファイアが設定されている場合、通常のmatch()ファンクションはキャプチャされたグループを返しませんが、RegExpのファンクションはexec()となります。 (他の場所の中で、hereを指摘した。)

覚えておくべきもう一つの漁獲量は、それがその場合には、nullを返し、なくなるまでexec()が一つの大きな配列-それが戻って続け試合で試合を返さないということです。

var pattern = /t(e)(s)t/g; // Alternatively, "new RegExp('t(e)(s)t', 'g');" 
var match;  

while (match = pattern.exec(text)) { 
    // Do something with the match (["test", "e", "s"]) here... 
} 

注意すべきもう一つは、RegExp.prototype.exec()RegExp.prototype.test()した文字列に正規表現を実行し、最初の結果を返すということです。

したがって、たとえば、あなたはこのような何かを行うことができます。すべての順次呼び出しは、文字列内の現在の位置に基づいて、RegExp.prototype.lastIndexの更新結果セットをステップ実行します。

ここに例があります: //例とパターンには4つの一致があります。 lastIndexのは0

pattern.test(text); // pattern.lastIndex = 4 
pattern.test(text); // pattern.lastIndex = 9 
pattern.exec(text); // pattern.lastIndex = 14 
pattern.exec(text); // pattern.lastIndex = 19 

// if we were to call pattern.exec(text) again it would return null and reset the pattern.lastIndex to 0 
while (var match = pattern.exec(text)) { 
    // never gets run because we already traversed the string 
    console.log(match); 
} 

pattern.test(text); // pattern.lastIndex = 4 
pattern.test(text); // pattern.lastIndex = 9 

// however we can reset the lastIndex and it will give us the ability to traverse the string from the start again or any specific position in the string 
pattern.lastIndex = 0; 

while (var match = pattern.exec(text)) { 
    // outputs all matches 
    console.log(match); 
} 

で始まり、あなたは(具体的には、ここではthe exec() functionのドキュメントだ)RegExpオブジェクトon the MDNを使用する方法についての情報を見つけることができます。

+3

execを使用するとg修飾子をリッスンしないようですが、サブマッチ/グループがサポートされます。結果は最初の一致になります(基本的にg修飾子は無視されます)。 –

+0

これについての説明が追加されました。複数の一致を得るためにexec()を繰り返し呼び出さなければなりません。 – hbw

+2

最も洗練されたソリューションではありません。 は私はこのような多少出力を期待していた。 [ \t [ "テスト"、 "E"、 "S"]、 \t [ "テスト"、 "E"、 "S"]、 \t [」 \t ["test"、 "e"、 "s"] ] –