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"
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>";
}
});
}
}
The easiest way to do that would be to actually regex for **(content)**
rather than just **
. You then replace that by <strong>(content)</strong>
and you're done.
You may also want to check out MarkdownSharp at https://code.google.com/p/markdownsharp, since that is really what you seem to want to use.
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