正则表达式提取包含特定单词的超链接

时间:2013-04-19 08:45:29

标签: regex

我需要从一段文本中提取包含网址中特定单词的超链接。实施例;

“这是一个带有指向某个页面的链接的文字。点击此链接<a href="/server/specificword.htm>this is a link to a page</a>即可查看该页面。此处的链接中没有”specificword“一词:<a href="/server/mypage.htm>this is a link without the word "specificword" in the url</a>

因此,我需要解析此文本,检查超链接以查看其中一个是否包含单词“specificword”,然后提取整个超链接。然后我会以此结束:

<a href="/server/specificword.htm>this is a link to a page</a>

我需要在网址中具有特定字符的超链接,例如。 /server/specificword.htm,不在链接文本

我试过的一个正则表达式就是这个:/(<a[^>]*>.*?</a>)|specificword/ 这将匹配文本中的所有超链接或“特定字”。如果文本有多个链接,没有“specificword”这个词,我也会得到这些。

另外,我尝试了这个,但它没有任何用处:

<a.*?href\s*=\s*["\']([^"\'>]*specificword[^"\'>]*)["\'][^>]*>.*?<\/a>

我的正则表达技巧在这里结束,任何帮助都会很棒......

4 个答案:

答案 0 :(得分:8)

尝试使用所有标签:

/<a [^>]*\bhref\s*=\s*"[^"]*SPECIFICWORD.*?<\/a>/

或仅用于链接(在第一个捕获组中):

/<a [^>]*\bhref\s*=\s*"([^"]*SPECIFICWORD[^"]*)/

如果你使用php,链接:

preg_match_all('/<a [^>]*\bhref\s*=\s*"\K[^"]*SPECIFICWORD[^"]*/', $text, $results);

答案 1 :(得分:6)

这个应该符合您的需求:

<a href="[^"]*?specificword.*?">.*?</a>

Demo


如果你想在你的主要焦点上允许其他属性,并且对内部空间更加谨慎,你可以尝试:

<a( [^>]*?)? href="[^"]*?specificword.*?"( .*?)?>.*?</a>

Demo


您当然也可以使用非捕获组(?:...)

<a(?: [^>]*?)? href="[^"]*?specificword.*?"(?: .*?)?>.*?</a>

Demo


最后,如果您想允许href属性的简单引号:

<a(?: [^>]*?)? href=(["'])[^\1]*?specificword.*?\1(?: .*?)?>.*?</a>

Demo


最后但并非最不重要:如果您想捕获网址,只需在[^\1]*?specificword.*?部分附近加上括号:

<a(?: [^>]*?)? href=(["'])([^\1]*?specificword.*?)\1(?: .*?)?>.*?</a>

Demo

答案 2 :(得分:3)

你试过的最后一个正则表达式差不多了。试试这个改动:

<a\s.*?href=["']([^"']*?specificword[^"']*?)[^>]*>.*?<\/a>

主要区别在于使量词“懒惰”。

答案 3 :(得分:2)

尝试此模式这是您想要的确切要求

(?=.*href=\"([^\"]*specificword[^"]*)")<a [^>]+>

如果你只想要url值使用Groups [1] 像:

Regex.match("input string",@"(?=.*href=\"([^\"]*specificword[^"]*)")<a [^>]+>").Groups[1].value;