Marc Still
Marc Still

Reputation: 95

C# Regex - Match and replace, Auto Increment

I have been toiling with a problem and any help would be appreciated.

Problem: I have a paragraph and I want to replace a variable which appears several times (Variable = @Variable). This is the easy part, but the portion which I am having difficulty is trying to replace the variable with different values.

I need for each occurrence to have a different value. For instance, I have a function that does a calculation for each variable. What I have thus far is below:

private string SetVariables(string input, string pattern){

    Regex rx = new Regex(pattern);
    MatchCollection matches = rx.Matches(input);
    int i = 1;
    if(matches.Count > 0)
    {
        foreach(Match match in matches)
        {
            rx.Replace(match.ToString(), getReplacementNumber(i));
            i++
        }
    }

I am able to replace each variable that I need to with the number returned from getReplacementNumber(i) function, but how to I put it back into my original input with the replaced values, in the same order found in the match collection?

Thanks in advance!

Marcus

Upvotes: 7

Views: 3446

Answers (1)

Mark Byers
Mark Byers

Reputation: 838806

Use the overload of Replace that takes a MatchEvaluator as its second parameter.

string result = rx.Replace(input, match => { return getReplacementNumber(i++); });

I'm assuming here that getReplacementNumber(int i) returns a string. If not, you will have to convert the result to a string.

See it working online: ideone

Upvotes: 10

Related Questions