C# Regex - Match and replace, Auto Increment

Posted by Marc Still on Stack Overflow See other posts from Stack Overflow or by Marc Still
Published on 2012-06-15T21:10:24Z Indexed on 2012/06/15 21:16 UTC
Read the original article Hit count: 287

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET