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 =)
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>
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++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With