交替替换子串

Jak*_*keJ 5 c# string markdown substring

我想知道是否有任何方法可以替换字符串中的子串,但在字符串之间交替替换它们.IE,匹配字符串的所有出现"**"并用下一个出现替换第一次"<strong>"出现"</strong>"(然后重复该模式).

输入将是这样的: "This is a sentence with **multiple** strong tags which will be **strong** upon output"

返回的输出将是: "This is a sentence with <strong>multiple</strong> strong tags which will be <strong>strong</strong> upon output"

Pao*_*sco 6

您可以使用Regex.Replace带有MatchEvaluator委托的重载:

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>";
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)