C# 查找标记之间的所有文本并修改每个找到的实例

C# finding all text between markers and modifying each found instance

我有一个来自外部来源的字符串,其中包含围绕重要文本的开始和结束标记(两个星号)。我在 html 文件中显示此文本,我需要首先使用 C# 解析字符串,并加粗任何标记的文本,包括标记。

希望下面显示了我正在努力完成的事情...

    public static void Main()
    {
        string orginalText = "Cat dog ** monkey ** lizard hamster ** fish ** frog";
    
        Console.WriteLine(ReplaceMarkedText(orginalText));
    }

    string ReplaceMarkedText(string text)
    {
        // This is the closest I've gotten so far, but it only works with one pair of asterisks.
        var matches = Regex.Match(text, @"\*\*([^)]*)\*\*").Groups;
        string newText = text.Replace("**", string.Empty);
        foreach (Group match in matches)
        {
           if (match.Value.Length > 0)
           {
                newText = newText.Replace(match.Value, "<b>**" + match.Value + "**</b>");
            }
        }

        return newText;
    }

我想在控制台输出中看到的内容:Cat dog <b>** monkey **</b> lizard hamster <b>** fish **</b> frog

使用

string Result = Regex.Replace(text, "\*{2}.*?\*{2}", "<b>$&</b>");

参见regex proof

解释

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  \*{2}                    '*' (2 times)
--------------------------------------------------------------------------------
  .*?                      any character except \n (0 or more times
                           (matching the least amount possible))
--------------------------------------------------------------------------------
  \*{2}                    '*' (2 times)