关于正则替换,有几点说明

这篇博文的重点是正则替换的一点注意事项。

(1)发送页面的时候

string html= "<a href='<table border='1'> <tr><th>Month</th><th>Savings</th></tr> <tr><td>January</td><td>$100</td> </tr></table>' target='_blank'>表格点击</a>";

html = Regex.Replace(html, "table.*?>", "table", RegexOptions.IgnoreCase);
html = Regex.Replace(html, "border='1'>", "border=1", RegexOptions.IgnoreCase);
html = Regex.Replace(html, "td>", "td", RegexOptions.IgnoreCase);
html = Regex.Replace(html, "b>", "b1", RegexOptions.IgnoreCase);
html = Regex.Replace(html, "tr>", "tr", RegexOptions.IgnoreCase);
html = Regex.Replace(html, "th>", "th", RegexOptions.IgnoreCase);

//注意b>替换的时候,不要直接替换成b,因为在接受页面接受的时候,如果还原回去,就是html = Regex.Replace(html, "b", "b>", RegexOptions.IgnoreCase);但是别的标签,比如table里面也有b字母,这样就会造成替换错乱了。

//html = html.Replace("<A", "a");//注意这里,直接用replace方法,如果html = html.Replace("<A", "a");没法替代,不如用正则的忽略大小写(regexoptions.ignorecase)用着简单。

(2)接收页面的时候:

id=Regex.Replace(id,"about:<table","",RegexOptions.IgnoreCase);//注意这里,因为发送的时候不是一段带有http://的链接,所以接收的时候会有错误(错误就是多加一个about:),这个时候如果想要正常的显示的话,需要把这个也一块替换掉
id = Regex.Replace(id, "td", "td>", RegexOptions.IgnoreCase);
id = Regex.Replace(id, "b1", "b>", RegexOptions.IgnoreCase);//这样接收的时候,因为b1一般数据里没有,也比较方便替换,当然也可以替换成更加不常用的,b1仅作中间过渡的量。
id = Regex.Replace(id, "tr", "tr>", RegexOptions.IgnoreCase);
id = Regex.Replace(id, "th", "th>", RegexOptions.IgnoreCase);
string html = "<html><body><table border='1'" + id + "</table></body></html>";//接的时候注意这个id,就是一系列的字符串。

posted on 2013-06-26 17:55  鸣动我心  阅读(215)  评论(0编辑  收藏  举报