从C#中的字符串中删除HTML标记和注释?

时间:2010-04-09 19:21:41

标签: c# html regex

如何从C#中的字符串中删除以'<'开头并以'>'结尾的所有内容。我知道可以用正则表达式来完成,但我对它不是很好。

3 个答案:

答案 0 :(得分:3)

我为最近的一个小项目快速写的标签模式就是这个。

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

我像这样使用它

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

可能需要修改它才能正确处理脚本或样式标记。

答案 1 :(得分:1)

非正则表达式选项:但它仍然无法解析嵌套标签!

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

答案 2 :(得分:1)

另一个非正则表达式,比正则表达式快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);
}