2011-06-17 50 views
7

我将html作为带有javascript和css代码块的字符串。.Net从html页面中删除javascript和css代码块

事情是这样的:

<script type="text/javascript"> 

    alert('hello world'); 

</script> 

<style type="text/css"> 
    A:link {text-decoration: none} 
    A:visited {text-decoration: none} 
    A:active {text-decoration: none} 
    A:hover {text-decoration: underline; color: red;} 
</style> 

但我不需要他们。我怎样才能删除与reqular表达式这些块?

回答

15

快速 'N' 脏的方法是这样的正则表达式:

var regex = new Regex(
    "(\\<script(.+?)\\</script\\>)|(\\<style(.+?)\\</style\\>)", 
    RegexOptions.Singleline | RegexOptions.IgnoreCase 
); 

string ouput = regex.Replace(input, ""); 

更好*(但可能更慢)的选择是使用HtmlAgilityPack

HtmlDocument doc = new HtmlDocument(); 
doc.LoadHtml(htmlInput); 

var nodes = doc.DocumentNode.SelectNodes("//script|//style"); 

foreach (var node in nodes) 
    node.ParentNode.RemoveChild(node); 

string htmlOutput = doc.DocumentNode.OuterHtml; 

*)对于关于为什么更好的讨论,请参见this thread

+3

你知道吗[托尼小马](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)? – GvS 2011-06-17 09:24:15

+1

@GvS:我知道在使用正则表达式处理HTML时可能会出现的问题。因此,对于大多数情况下,我会强烈建议像HtmlAgilityPack这样的html解析器,但这取决于情况。如果是一次性删除脚本和样式块,并且我知道输入是有效的html,那么我的上述正则表达式就足够了,尤其是因为'

1

只要找一个开放的<script标记,然后删除它和关闭/script>标记之间的所有内容。

同样的风格。 See Google为字符串操作提示。

+0

不一样,如果您的代码文件撰写(“”)在其 – 2011-06-17 10:58:24

+0

是它足以只是这样做的安全感的工作? (阻止JavaScript执行)? – Bamboo 2014-05-23 07:23:54

2

使用HTMLAgilityPack获得更好的结果

或尝试这个功能

public string RemoveScriptAndStyle(string HTML) 
{ 
    string Pat = "<(script|style)\\b[^>]*?>.*?</\\1>"; 
    return Regex.Replace(HTML, Pat, "", RegexOptions.IgnoreCase | RegexOptions.Singleline); 
} 
1

我做了我的自行车),他可能不会像HtmlAgilityPack是正确的,但它的速度要快得多了约5-6倍于400 kb的页面。另外,还要小写符号和删除数字(标记生成器制造)

private static readonly List<byte[]> SPECIAL_TAGS = new List<byte[]> 
                  { 
                   Encoding.ASCII.GetBytes("script"), 
                   Encoding.ASCII.GetBytes("style"), 
                   Encoding.ASCII.GetBytes("noscript") 
                  }; 

    private static readonly List<byte[]> SPECIAL_TAGS_CLOSE = new List<byte[]> 
                    { 
                     Encoding.ASCII.GetBytes("/script"), 
                     Encoding.ASCII.GetBytes("/style"), 
                     Encoding.ASCII.GetBytes("/noscript")}; 

public static string StripTagsCharArray(string source, bool toLowerCase) 
    { 
     var array = new char[source.Length]; 
     var arrayIndex = 0; 
     var inside = false; 
     var haveSpecialTags = false; 
     var compareIndex = -1; 
     var singleQouteMode = false; 
     var doubleQouteMode = false; 
     var matchMemory = SetDefaultMemory(SPECIAL_TAGS); 
     for (int i = 0; i < source.Length; i++) 
     { 
      var let = source[i]; 
      if (inside && !singleQouteMode && !doubleQouteMode) 
      { 
       compareIndex++; 
       if (haveSpecialTags) 
       { 
        var endTag = CheckSpecialTags(let, compareIndex, SPECIAL_TAGS_CLOSE, ref matchMemory); 
        if (endTag) haveSpecialTags = false; 
       } 
       if (!haveSpecialTags) 
       { 
        haveSpecialTags = CheckSpecialTags(let, compareIndex, SPECIAL_TAGS, ref matchMemory); 
       } 
      } 
      if (haveSpecialTags && let == '"') 
      { 
       doubleQouteMode = !doubleQouteMode; 
      } 
      if (haveSpecialTags && let == '\'') 
      { 
       singleQouteMode = !singleQouteMode; 
      } 
      if (let == '<') 
      { 
       matchMemory = SetDefaultMemory(SPECIAL_TAGS); 
       compareIndex = -1; 
       inside = true; 
       continue; 
      } 
      if (let == '>') 
      { 
       inside = false; 
       continue; 
      } 
      if (inside) continue; 
      if (char.IsDigit(let)) continue; 
      if (haveSpecialTags) continue; 
      array[arrayIndex] = toLowerCase ? Char.ToLowerInvariant(let) : let; 
      arrayIndex++; 
     } 
     return new string(array, 0, arrayIndex); 
    } 

    private static bool[] SetDefaultMemory(List<byte[]> specialTags) 
    { 
     var memory = new bool[specialTags.Count]; 
     for (int i = 0; i < memory.Length; i++) 
     { 
      memory[i] = true; 
     } 
     return memory; 
    }