c# – How to search tags using Regular Expression?

Question:

I would like to create a regular expression that looks for the tags:

<b>, <p>, <i>

How would you do this in regular expression?

Answer:

You can use the expression @"\<([\/?\s?\w]+)\>

See the example below.

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {

        foreach (Match match in Regex.Matches("<p> olá </ br>  nova linha </p>",  @"\<([\/?\s?\w]+)\>"))
        {
            Console.WriteLine("{0}", match.Value);
        }
    }
}

https://dotnetfiddle.net/2flyzC

You can Replace directly with Regex

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string texto = "<p> olá </ br>  nova linha </p>";

        var match = Regex.Replace(texto,  @"\<([\/?\s?\w]+)\>", "");            

        Console.WriteLine(match);

    }
}

https://dotnetfiddle.net/NO2Jc4

Scroll to Top