Remove HTML tags and comments from a string in C #?

How to remove everything from '<' to '>' from a string in C #. I know that this can be done with regex , but I don't understand that very well.

+3
source share
3 answers

The tag template that I quickly wrote for a recent small project is one.

string tagPattern = @"<[!--\W*?]*?[/]*?\w+.*?>";

I used it like that

MatchCollection matches = Regex.Matches(input, tagPattern);
foreach (Match match in matches)
{
    input = input.Replace(match.Value, string.Empty);
}

It will probably need to be changed in order to properly handle script or style tags.

+3
source

Optional: but it still won’t parse nested tags!

public static string StripHTML(string line)
        {
            int finished = 0;
            int beginStrip;
            int endStrip;

            finished = line.IndexOf('<');
            while (finished != -1)
            {
                beginStrip = line.IndexOf('<');
                endStrip = line.IndexOf('>', beginStrip + 1);
                line = line.Remove(beginStrip, (endStrip + 1) - beginStrip);
                finished = line.IndexOf('<');
            } 

            return line;
        }
+1
source

, 8 , :

public static string StripTagsCharArray(string source)
{
    char[] array = new char[source.Length];
    int arrayIndex = 0;
    bool inside = false;
    for (int i = 0; i < source.Length; i++)
    {
        char let = source[i];
        if (let == '<')
        {
            inside = true;
            continue;
        }
        if (let == '>')
        {
            inside = false;
            continue;
        }
        if (!inside)
        {
            array[arrayIndex] = let;
            arrayIndex++;
        }
    }
    return new string(array, 0, arrayIndex);
}
+1

Source: https://habr.com/ru/post/1740511/


All Articles