2009-05-26 45 views
0

我想知道如何替換每個匹配不同文本? 比方說,原文是:用ActionScript 3中的不同文本替換每個RegExp匹配

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

..和我們有一個正則表達式,如:

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

謝謝,但不會工作,因爲在實際的代碼不搜索單詞「查找」(我給了這個例子,使問題更清晰)。它搜索的東西就像。*?所以;你的方式創造了一個無限循環.. – 2009-05-26 21:42:30

0

不確定關於actionscript,但在許多其他正則表達式實現中,您通常可以傳遞一個回調函數來執行每個匹配和替換的邏輯。

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