", ""}; And I want to do som...">

Regular expression padding

So, I have this line []:

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 just ask if it is possible to loop through Regex any way and therefore be able to replace string with different values ​​that are stored in string[] . It doesn't have to be a foreach , and I know this code is ridiculous, but I told him to ask the clearest question. Please comment on any questions you have for me.

Thanks for the help =)

+6
source share
2 answers

You can list replacement strings. You should tailor it to suit your needs, but I think something like this will 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++; } 
+6
source

I will skip the discussion of “don't parse HTML with regex” and suppose you're looking at the overloads for Regex.Replace that accept the MatchEvaluator delegate.

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

This MSDN page provides an example of entering an index number in replacement text. You should be able to use the index in your array to get the replacement text.

Here is 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> 
+6
source

All Articles