Alternating replace of substrings
c#, markdown, string, substring
Solution
You can use the overload of `Regex.Replace` that takes a `MatchEvaluator` delegate:
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string toReplace = "This is a sentence with **multiple** strong tags which will be **strong** upon output";
int index = 0;
string replaced = Regex.Replace(toReplace, @"\*\*", (m) => {
index++;
if (index % 2 == 1) {
return "<strong>";
} else {
return "</strong>";
}
});
}
}
Problem
I was wondering if there is any way that I can replace substrings within a string but alternate between the string to replace them with. I.E, match all occurences of the string `"**"` and replace the first occurence with `"<strong>"` and the next occurence with `"</strong>"` (And then repeat that pattern). The input would be something like this: `"This is a sentence with **multiple** strong tags which will be **strong** upon output"` And the output returned would be: `"This is a sentence with <strong>multiple</strong> strong tags which will be <strong>strong</strong> upon output"`