Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternating replace of substrings

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"

like image 411
JakeJ Avatar asked Oct 09 '22 05:10

JakeJ


2 Answers

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>";
            }
        });
    }
}
like image 82
Paolo Tedesco Avatar answered Oct 12 '22 10:10

Paolo Tedesco


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.

like image 40
Roy Dictus Avatar answered Oct 12 '22 11:10

Roy Dictus