代码之家  ›  专栏  ›  技术社区  ›  Onur Yıldırım

将每个regexp替换为actionscript 3中的不同文本

  •  0
  • Onur Yıldırım  · 技术社区  · 15 年前

    我想知道如何更换 每场比赛 用一个 不同的 文本? 假设源文本是:

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

    …我们有一个regex,比如:

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

    现在,我需要用不同的文本替换每个匹配项(例如):

    var replacement:String = "replacement_" + increment.toString();
    

    所以输出是这样的:

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

    感谢您的帮助。

    4 回复  |  直到 15 年前
        1
  •  3
  •   Robert Sköld    15 年前

    您还可以使用替换函数,如下所示:

    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();
    } );
    
        2
  •  1
  •   Onur Yıldırım    15 年前

    我终于想出了一个解决办法。 如果有人需要:

    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++;
    }
    

    不管怎样,谢谢…

        3
  •  0
  •   ennuikiller    15 年前

    去掉g(全局)标志,用适当的替换字符串重复搜索。循环直到搜索失败

        4
  •  0
  •   patjbs    15 年前

    不确定actionscript,但在许多其他regex实现中,通常可以传递一个回调函数,该函数将为每个匹配和替换执行逻辑。