7

So I have this string[]:

string[] middleXMLTags = {"</Table1><Table2>", "</Table2><Table3>"};

And I want to do something like this with it:

int i = 0;
foreach (regex where it finds the replacement string)
{
    response = Regex.Replace(response, "</Table><Table>", middleXMLTags[i]);
    i++;
}
response = Regex.Replace(response, "<Table>", <Table1>);
response = Regex.Replace(response, "</Table>", </Table3>);

Ultimately, I'm just asking if it's possible to somehow loop through a Regex, and therefore being able to replace the string with different values that are stored in a string[]. It doesn't have to be a foreach loop, and I know that this code is ridiculous, but I put it hear to ask the clearest possible question. Please comment any questions you have for me.

Thanks for all help =)

Ian Best
  • 510
  • 1
  • 11
  • 23

2 Answers2

9

I'll skip the "don't parse HTML with Regex" discussion and suggest that you look at the overloads for Regex.Replace that take a MatchEvaluator delegate.

Basically, you can pass a delegate to the Replace() method that gets called for each match and returns the replacement text.

This MSDN page gives an example putting the index number into the replacement text. You should be able to use the index into your array to get the replacement text.

Here's a sample reflecting your example:

string[] middleXMLTags = {"</Table1><Table2>", "</Table2><Table3>"};

string response = "</Table><Table><foo/></Table><Table>";
Console.WriteLine(response);
int i = 0;

response = Regex.Replace(response,@"</Table><Table>",m=>middleXMLTags[i++]);
Console.WriteLine(response);

Output:

</Table><Table><foo/></Table><Table>
</Table1><Table2><foo/></Table2><Table3>
Mark Peters
  • 17,205
  • 2
  • 21
  • 17
  • This line is awesome and deserves more points: response = Regex.Replace(response,@"",m=>middleXMLTags[i++]);
    – Richard Sep 17 '13 at 13:34
7

You can enumerate through the replacement strings. You'd have to tailor it to suit your needs, but I imagine something like this would work.

Regex needle = new Regex("\[letter\]");
string haystack = "123456[letter]123456[letter]123456[letter]";
string[] replacements = new string[] { "a", "b", "c" };

int i = 0;
while (needle.IsMatch(haystack))
{
    if (i >= replacements.Length)
    {
        break;
    }

    haystack = needle.Replace(haystack, replacements[i], 1);
    i++;
}
Tim
  • 857
  • 6
  • 13
  • 1
    One note on this solution is that this will match overlapping patterns as well as match any text from earlier replacements. This may or may not be desired. – Mark Peters Feb 27 '13 at 13:23