使用正则表达式将Html转换为纯文本

在网页刚流行起来的时候,提取html中的文本有一个简单的方法,就是将html文本(包含标记)中的所有以“<”符号开头到以“>”符号之间的内容去掉即可。
但对于现在复杂的网页而言,用这种方法提取出来的文本会有大量的空格、空行、script段落、还有一些html转义字符,效果很差。
下面用正则表达式来提取html中的文本,
代码的实现的思路是:
a、先将html文本中的所有空格、换行符去掉(因为html中的空格和换行是被忽略的)
b、将标记中的所有内容去掉
c、将)", string.Empty, RegexOptions.IgnoreCase);

 //remove all styles
 result = Regex.Replace(result, @"<( )*style([^>])*>", ")", string.Empty, RegexOptions.IgnoreCase);

 //insert tabs in spaces of tags
 result = Regex.Replace(result, @"<( )*td([^>])*>", " ", RegexOptions.IgnoreCase);

 //insert line breaks in places of
and

  • tags
     result = Regex.Replace(result, @"<( )*br( )*>", "/r", RegexOptions.IgnoreCase);
     result = Regex.Replace(result, @"<( )*li( )*>", "/r", RegexOptions.IgnoreCase);

     //insert line paragraphs in places of and

    tags
     result = Regex.Replace(result, @"<( )*tr([^>])*>", "/r/r", RegexOptions.IgnoreCase);
     result = Regex.Replace(result, @"<( )*p([^>])*>", "/r/r", RegexOptions.IgnoreCase);

     //remove anything thats enclosed inside < >
     result = Regex.Replace(result, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);

     //replace special characters:
     result = Regex.Replace(result, @"&", "&", RegexOptions.IgnoreCase);
     result = Regex.Replace(result, @" ", " ", RegexOptions.IgnoreCase);
     result = Regex.Replace(result, @"<", "<", RegexOptions.IgnoreCase);
     result = Regex.Replace(result, @">", ">", RegexOptions.IgnoreCase);
     result = Regex.Replace(result, @"&(.{2,6});", string.Empty, RegexOptions.IgnoreCase);

     //remove extra line breaks and tabs
     result = Regex.Replace(result, @" ( )+", " ");
     result = Regex.Replace(result, "(/r)( )+(/r)", "/r/r");
     result = Regex.Replace(result, @"(/r/r)+", "/r/n");

     return result;
     }

     }//end class
    }//end namespace

  • 你可能感兴趣的:(002-数据,正则表达式,html,tabs,attributes,string,styles)