2009-05-26 5 views
0

の置換方法を知りたい異なるのテキストを置き換えますか?ActionScript 3の各RegExpの一致を別のテキストに置き換えます

var strSource:String = "find it and replace what you find."; 

..and我々のような正規表現を持っている:私は(例えば)異なるテキストで各試合を交換する必要があり、今

var re:RegExp = /\bfind\b/g; 

をのは、ソーステキストがあるとしましょう
var replacement:String = "replacement_" + increment.toString(); 

ので、出力はのようになります。

output = "replacement_1 it and replace what you replacement_2"; 

答えて

1

私は ...ついに解決策を考え出した、誰もが必要な場合はここでは、次のとおりです。

var re:RegExp = /(\b_)(.*?_ID\b)/gim; 
var increment:int = 0; 
var output:Object = re.exec(strSource); 
while (output != null) 
{ 
    var replacement:String = output[1] + "replacement_" + increment.toString(); 
    strSource = strSource.substring(0, output.index) + replacement + strSource.substring(re.lastIndex, strSource.length); 
    output = re.exec(strSource); 
    increment++; 
} 

とにかく感謝...

0

g(グローバル)フラグをオフにして、適切な置換文字列で検索を繰り返します。検索が失敗するまでループする

+0

実際のコードでは「検索」という単語を検索しないため(この例では質問を明確にしています)、機能しません。それは〜のようなものを探します。そう;あなたの方法は無限ループを作成します.. –

0

アクションスクリプトについてはわかりませんが、他の多くの正規表現の実装では、通常、それぞれの一致と置換のロジックを実行するコールバック関数を渡すことができます。

3

ます。また、このような何かを置換機能を使用できます。

var increment : int = -1; // start at -1 so the first replacement will be 0 
strSource.replace(/(\b_)(.*?_ID\b)/gim , function() { 
    return arguments[1] + "replacement_" + (increment++).toString(); 
}); 
関連する問題