Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a regex replace

Tags:

c#

regex

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 =)

like image 223
Ian Best Avatar asked Feb 26 '13 17:02

Ian Best


2 Answers

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>
like image 77
Mark Peters Avatar answered Nov 02 '22 12:11

Mark Peters


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++;
}
like image 23
Tim Avatar answered Nov 02 '22 12:11

Tim