简体   繁体   中英

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

How do I remove everything beginning in '<' and ending in '>' from a string in C#. I know it can be done with regex but I'm not very good with it.

The tag pattern I quickly wrote for a recent small project is this one.

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

I used it like this

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

It would likely need to be modified to correctly handle script or style tags.

Another non-regex code that works 8x faster than regex:

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

Non regex option: 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;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM