正则表达式删除除允许之外的HTML属性和标记

时间:2015-06-18 20:27:15

标签: c# html asp.net regex

我需要按照特定规则使用HTML标记验证输入文本。

        string result = string.Empty;
        string acceptableTags = "h1|h2|h3|h4|h5|h6|br|img|video|cut|a";
        string acceptableAtributes = "alt|href|height|width|align|valign|src|class|id|name|title";
        string stringPattern = @"</?(?(?=" + acceptableTags + @")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:(["",']?).*?\1?)?)*\s*/?>";
        result = Regex.Replace(msg, stringPattern, "");
        stringPattern = @"\s(?!(" + acceptableAtributes + @"))\w+(\s*=\s*[""|']?[/.,#?\w\s:;-]+[""|']?)";
        result = Regex.Replace(result, stringPattern, "");
        return result;

这几乎是工作代码。例如,它会删除此处的onload属性

<img src="pic.jpg" onload=" alert(123)">

但不会在这里

<img src="pic.jpg"onload="alert(123)">

P.S。为此设置一个正则表达式会更好,但我不太了解它。

1 个答案:

答案 0 :(得分:0)