Home > Back-end >  C# finding all text between markers and modifying each found instance
C# finding all text between markers and modifying each found instance

Time:11-21

I have a string coming from an external source that contains start and end markers (two asterisks) around important text. I'm displaying this text in an html file and I need to parse the string first with C# and bold any marked text including the markers.

Hopefully the below shows what I'm trying to accomplish...

    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;
    }

What I want to see in console output: Cat dog <b>** monkey **</b> lizard hamster <b>** fish **</b> frog

CodePudding user response:

Use

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

See regex proof.

EXPLANATION

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