读书人

正则表达式采撷

发布时间: 2012-07-05 07:59:18 作者: rapoo

正则表达式采集
大家 好,我现在需要 作一个简单的采集器
主要是匹配源代码中的 超连接
这是一个较烦的。

HTML code
<a class="costdown" href="http://order.xiaomi.com/static/re" onclick="_gaq.push(['_trackEvent', '首页广告点击', '官翻版购买通道']);">官翻版购买通道</a>  

-----我只要匹配其中有 “官翻版购买通道” 和链接“http://order.xiaomi.com/static/re”

HTML code
<a style="margin-left:20px" href="http://www.xiaomi.com/about" >关于小米</a>
匹配: 关于小米 --http://www.xiaomi.com/about

主要是匹配关键词 与连接的地址。怎么实现

[解决办法]
(?i)<a\b[^>]*?href=(['"]?)(?<href>[^'"]+)\1[^>]*?>(?<txt>[^<>]+)</a>

取Groups["href"]和Groups["txt"] 就是你想要的
[解决办法]
C# code
 string input = @"<a class=""costdown"" href=""http://order.xiaomi.com/static/re"" onclick=""_gaq.push(['_trackEvent', '首页广告点击', '官翻版购买通道']);"">官翻版购买通道</a>  <a style=""margin-left:20px"" href=""http://www.xiaomi.com/about"" >关于小米</a>";             Dictionary<string, string> dic = new Dictionary<string, string>();            foreach (Match m in Regex.Matches(input, @"(?is)<a\b[^>]*?href=([""']?)([^""']*?)\1[^>]*?>(.*?)</a>"))            {                dic.Add(m.Groups[2].Value, m.Groups[3].Value);            }            foreach (var m in dic)            {                Console.WriteLine(m.Key + "\t" + m.Value);            }/*http://order.xiaomi.com/static/re       官翻版购买通道http://www.xiaomi.com/about            关于小米*/ 

读书人网 >asp.net

热点推荐