C#使用正则表达式过滤HTML代码
对于一些特殊的功能,我们需求对其HTML代码进行过滤,比如不可以进行HTML代码留言等地方.
本文为大家介绍在asp.net下使用C#语言实现的正则表达式过滤HTML代码
以下是过滤HTML代码功能方法.
public static String getTxtWithoutHTMLElement (String element)
{
// String reg="< [^< |^>]+>";
// return element.replaceAll(reg,"");
if(null==element||"".equals(element.trim()))
{
return element;
}
Pattern pattern=Pattern.compile("< [^< |^>]*>");
Matcher matcher=pattern.matcher(element);
StringBuffer txt=new StringBuffer();
while(matcher.find())
{
String group=matcher.group();
if(group.matches("< [\\s]*>"))
{
matcher.appendReplacement(txt,group);
}
else
{
matcher.appendReplacement(txt,"");
}
}
matcher.appendTail(txt);
repaceEntities(txt,"&","&");
repaceEntities(txt,"< ","< ");
repaceEntities(txt,">",">");
repaceEntities(txt,""","\"");
repaceEntities(txt," ","");
return txt.toString();
}
下面是调用方法进行测试
public void testGetTxtWithoutHTMLElement ()
{
assertEquals("test",ExcelHssfView.getTxtWithoutHTMLElement("< a href='a/test'>test< /a>"));
assertEquals("test",ExcelHssfView.getTxtWithoutHTMLElement("< a href='a/test'>test"));
assertEquals("test",ExcelHssfView.getTxtWithoutHTMLElement("< input type='text'>test< /input>"));
assertEquals("test",ExcelHssfView.getTxtWithoutHTMLElement("< p>test"));
assertEquals("test",ExcelHssfView.getTxtWithoutHTMLElement("< table>< tr>< td>test< /td>< /tr>< /table>"));
assertEquals("te< st",ExcelHssfView.getTxtWithoutHTMLElement("< p>te< st"));
assertEquals("te>st",ExcelHssfView.getTxtWithoutHTMLElement("< p>te>st"));
assertEquals("tst",ExcelHssfView.getTxtWithoutHTMLElement("< p>t< e>st"));
assertEquals("t< st",ExcelHssfView.getTxtWithoutHTMLElement("< p>t< < e>st"));
assertEquals("< >test",ExcelHssfView.getTxtWithoutHTMLElement("< p>< >test"));
assertEquals("< >test",ExcelHssfView.getTxtWithoutHTMLElement("< p>< >test"));
assertEquals("< < >test",ExcelHssfView.getTxtWithoutHTMLElement("< p>< < >test"));
assertEquals("test",ExcelHssfView.getTxtWithoutHTMLElement("< table>< tr>< td> test< /td>< /tr>< /table>"));
}
原文转自网站制作教程网:http://www.web2bar.cn/Article/3495.aspx