如何将这些字符串与正则表达式匹配?
问题描述:
<div>
<a href="http://website/forum/f80/ThreadLink-new/" id="thread_gotonew_565407"><img class="inlineimg" src="http://website/forum/images/buttons/firstnew.gif" alt="Go to first new post" border="0" /></a>
[MULTI]
<a href="http://website/forum/f80/ThreadLink/" id="thread_title_565407" style="font-weight:bold">THREAD TITLE</a>
</div>
我知道一个事实,我感兴趣的链接是要去大胆:如何将这些字符串与正则表达式匹配?
font-weight:bold
但是链接本身到来之前。我该如何将能够同时匹配链接地址:
http://website/forum/f80/ThreadLink/
和主题标题:
THREAD TITLE
编辑:Internet Explorer的HTML代码非常不同:
<A style="FONT-WEIGHT: bold" id=thread_title_565714
href="http://LinkAddress-565714/">ThreadTitle</A> </DIV>
答
试试这个:
ThreadTitle
<A style="FONT-WEIGHT: bold" id=(?<id>.*?)[\s\S]*? href="(?<url>.*?)">(?<title>.*?)</A>
所以,你可以使用:
Regex link = new Regex(@"<A style=""FONT-WEIGHT: bold"" id=(?<id>.*?)[\s\S]*? href=""(?<url>.*?)"">(?<title>.*?)</A>");
foreach (Match match in link.Matches(input))
{
Console.WriteLine(
"Id={0}, Url={1}, Title={2}",
match.Groups["id"].Value,
match.Groups["url"].Value,
match.Groups["title"].Value);
}
答
.*<a href="(.*?)".*style="font-weight:bold">(.*?)</a>
比赛第1组:URL 比赛第2组:主题标题
这将匹配任何大胆的链接。如果你想匹配一个特定的,用这些值替换(。*?)。
答
<a href="([^"]*)"[^>]*style="[^"]*font-weight:bold[^"]*"[^>]*>([^<]*)</a>
大致相同的以前的答案,但我已经更换了他们的.*
与[^"]*
等。在第一场比赛,这阻止它匹配下一个双引号符号以外的任何东西。如果不这样做,如果你能匹配的情况太多了,其中输入是这样的:
<a href="#dont_match_me">Don't match me</a><br/>
<a href="http://website/forum/f80/ThreadLink/ style="font-weight:bold">THREAD TITLE</a>
感谢,也如果链接是:linkaddress-ID,将有可能把它适合的正则表达式匹配,所以我没有打破其他团体的额外gro??所以fulllink,标题,linkid(数字后 - :linkaddress-1234) – 2009-10-20 01:33:29
请参阅编辑的答案;而已? – 2009-10-20 01:38:44
谢谢鲁本,现在就来看看吧。 – 2009-10-20 01:40:23