標籤:head desc 連結 option line title log str news
擷取單個a中href的值:
string str = "<a href=\"http://www.itsve.com\">下載</a>"; string reg = @"<a[^>]*href=([""‘])?(?<href>[^‘""]+)\1[^>]*>"; var item = Regex.Match(str, reg, RegexOptions.IgnoreCase); Console.WriteLine(item.Groups["href"].Value);
擷取多個a中的href的值:
string str = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<head>" + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>" + "<meta content=\"怎樣用c Regex解析HTML中a 超連結 址 .NET技術 ASP.NET\" name=\"Keywords\"/>" + "<meta content=\"是用c Regex 是在後台 不是jsRegex 是要擷取a href屬性值\" name=\"description\"/>" + "<title>怎樣用c#Regex解析HTML中a的超連結位址 - .NET技術 / ASP.NET</title>" + "<li><a href=\"http://news.csdn.net/\" target=\"_blank\">資訊</a>|</li>" + "<li><a href=\"http://mobile.csdn.net/\" target=\"_blank\">移動</a>|</li>" + "<li><a href=\"http://cloud.csdn.net/\" target=\"_blank\">雲端運算</a>|</li>" + "<link href=\"http://c.csdn.net/bbs/t/5/t5.css\" rel=\"stylesheet\" type=\"text/css\" />" + "<link href=\"http://www.csdn.net/images/favicon.ico\" rel=\"SHORTCUT ICON\" />"; Regex reg = new Regex(@"(?is)<a[^>]*?href=([‘""\s]?)(?<href>[^‘""\s]*)\1[^>]*?>"); MatchCollection match = reg.Matches(str); foreach (Match m in match) { Response.Write(m.Groups["href"].Value + "<br/>"); }
//C#使用Regex擷取HTML代碼中a標籤裡包含指定尾碼的href的值,運算式如下:Regex regImg = new Regex(@"(?is)<a[^>]*?href=([‘""\s]?)(?<href>([^‘""\s]*\.doc)|([^‘""\s]*\.docx)|([^‘""\s]*\.xls)|([^‘""\s]*\.xlsx)|([^‘""\s]*\.ppt)|([^‘""\s]*\.txt)|([^‘""\s]*\.zip)|([^‘""\s]*\.rar)|([^‘""\s]*\.gz)|([^‘""\s]*\.bz2))\1[^>]*?>"
c#正則擷取html裡面a標籤href的值