ASP.NET提取超链接的正在表达式用法

来源:互联网 发布:软件著作权样例 编辑:程序博客网 时间:2024/05/01 17:08

由于在项目中要对超链接进行处理,分别用到下面三个函数,小生在此献丑了,大家如有好的解决办法,敬请分享。
1.提取HTML文档中的超链接
        public static string ExtractLink(string strHtml)
        {
            string pattern = @"<a[/w/W]*?</a>";
            MatchCollection mc = Regex.Matches(strHtml, pattern);
            StringBuilder sb = new StringBuilder();
            foreach (Match m in mc)
            {
                sb.Append(m.ToString());
            }
            return sb.ToString();
        }
2.提取超链接内容
        public static string getLinkText(string strHtml)
        {
            string LinkText = "";
            Regex reg = newRegex(@"(?m)<a[^>]*>(?<a>(?:/w|/W)*?)</a[^>]*>",RegexOptions.Multiline | RegexOptions.IgnoreCase);
            Match mc = reg.Match(strHtml);
            if (mc.Success)
                LinkText = mc.Groups["a"].Value.Trim();
            return LinkText;
        }
3.获取连接地址
        public static string getLinkHref(string strHtml)
        {
            string pattern = @"http(s)?://([/w-]+/.)+[/w-]+(/[/w- ./?%&=]*)?";
            MatchCollection mc = Regex.Matches(strHtml, pattern);
            StringBuilder sb = new StringBuilder();
            foreach (Match m in mc)
            {
                sb.Append(m.ToString());
            }
            return sb.ToString();
        }