一个网页里面有多链接
比如: <a href=../20/index.html>广告</a>
<a href=../aa/index.html>摄影</a>
求一个正则表达列出这些链接,列出来,同时能取到“广告”和“摄影”另外一组链接:<a href =../6/content_2.htm>项目1</a>,<a href =../5/content_1.htm>项目2</a>也要取出相关的链接和title
比如: <a href=../20/index.html>广告</a>
<a href=../aa/index.html>摄影</a>
求一个正则表达列出这些链接,列出来,同时能取到“广告”和“摄影”另外一组链接:<a href =../6/content_2.htm>项目1</a>,<a href =../5/content_1.htm>项目2</a>也要取出相关的链接和title
(?<=<a.*?>).*?(?=</a>)
Regex rg = new Regex("<a href="(\\w+)">(\\w+) </a>");//注意空格哦。少個空格會錯的。淡然你可以用.*來匹配空格,隨意的
bool b = rg.IsMatch(s);//我測試時,這裡返回true
Match m = rg.Match(s); string url= m.Groups[1];//這樣取的值,就分別是正則表達式中小括號的位置。一個小括號一個Groups。所以就可以取出你要的數據了 string title= m.Groups[2];
foreach (match m in mc)
{
m.groups["link"].value; //链接
m.groups["title"].value; //title
}
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.IO;namespace CSharpTest
{ class B
{ static void Main()
{ string str = @"<a href =../6/content_2.htm>项目1 </a>, <a href =../5/content_1.htm>项目2 </a> ";
Regex re = new Regex(@".*?href\s*=(?<href>[^>]*)>(?<title>[^<]*).*?");
MatchCollection mc=re.Matches(str);
foreach(Match m in mc)
Console.WriteLine("{0} {1}",m.Groups["href"].Value,m.Groups["title"].Value);
}
}}
foreach (match m in mc)
{
m.groups["link"].value; //链接
m.groups["title"].value; //title
}
有这种需求,一开始就要提出来 Regex reg = new Regex(@"(?is)<a[^>]*?href\s*=\s*(['""]?)(?=[^'""\s>]*?(?:content_|index\.html))(?<url>[^'""\s>]+)\1[^>]*>(?<text>(?:(?!</?a\b).)*)</a>");
MatchCollection mc = reg.Matches(yourStr);
foreach (Match m in mc)
{
richTextBox2.Text += m.Groups["url"].Value + "\n";
richTextBox2.Text += m.Groups["text"].Value + "\n";
}