0

I'd like to know how to replace each match with a different text? Let's say the source text is:

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

..and we have a regex such as:

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

Now, I need to replace each match with different text (for example):

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

So the output would be something like:

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

Any help is appreciated..

4 Answers 4

3

You could also use a replacement function, something like this:

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();
} );
Sign up to request clarification or add additional context in comments.

Comments

1

I came up with a solution finally.. Here it is, if anyone needs:

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

Thanks anyway...

Comments

0

leave off the g (global) flag and repeat the search with the appropriate replace string. Loop until the search fails

1 Comment

Thanks but that won't work because in the actual code doesn't search for the word "find" (I gave this example to make the question clearer). It searches for something like .*? so; your way creates an endless loop..
0

Not sure about actionscript, but in many other regex implementations you can usually pass a callback function that will execute logic for each match and replace.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.