Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex - Match and replace, Auto Increment

Tags:

c#

asp.net

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

like image 791
Marc Still Avatar asked Jun 15 '12 21:06

Marc Still


1 Answers

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

like image 165
Mark Byers Avatar answered Oct 03 '22 17:10

Mark Byers