2009-05-26 79 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(); 
});