代码改变世界

正则表达式收集与C#方式实现

2013-01-09 14:27  苏飞  阅读(1151)  评论(0编辑  收藏  举报

更多 :http://www.sufeinet.com/thread-1898-1-1.html

1.取出所有的 A标签

<a[^>]+>(.*?)</a>

2.取出A标签里面的属性

 //会取出所有的A标签里面的属性
<a[^>]+>

3.检查是否存在content的Meta

<meta([^<]*)content=([^<]*)>(.*?)

4.检查是否存在rel的a

<a([^<]*)rel=([^<]*)>(.*?)

5.获取时间的正则表达式

\s\d{1,4}-\d{1,2}-\d{1,2}

6.获取以,分开的数字的正则

\d{1,100}([,]*\d{1,100})*

7.匹配所有的Script标签

<script[^>]*?>.*?</script>

8.匹配所有的noScript标签

<noscript[^>]*?>.*?</noscript>

9. 匹配所有的href标签

href=["'\s]?(.*?)["'\s>]

10.取出Html的编码

Match meta = Regex.Match(html, "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase | RegexOptions.Multiline);
string charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty;

11.过滤所有Html代码的方法

 /// <summary>
/// 过滤html标签
/// </summary>
/// <param name="strHtml">html的内容</param>
/// <returns></returns>
public static string StripHTML(string stringToStrip)
{
// paring using RegEx //
stringToStrip = Regex.Replace(stringToStrip, "</p(?:\\s*)>(?:\\s*)<p(?:\\s*)>", "\n\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
stringToStrip = Regex.Replace(stringToStrip, "<br(?:\\s*)/>", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
stringToStrip = Regex.Replace(stringToStrip, "\"", "''", RegexOptions.IgnoreCase | RegexOptions.Compiled);
stringToStrip = StripHtmlXmlTags(stringToStrip);
return stringToStrip;
}

private static string StripHtmlXmlTags(string content)
{
return Regex.Replace(content, "<[^>]+>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
//使用访求
string str = StripHTML(html);

12.验证IP地址的正则表达式

\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}

13.验证身份证15位和18位

\d{17}[\d|X]|\d{15}

14.验证URL

http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

15.验证电子邮件

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

16.验证固定电话

(\(\d{3}\)|\d{3}-)?\d{8}

17.邮编

    \d{6}