根据anchortext获取超链接的URL

时间:2018-05-24 19:04:21

标签: regex

因此,我尝试使用包含单词blog的每个链接获取URL作为锚文本。

EG:

<a href="http://asdas.com/blog">this is our blog</a>
<a href="http://asdas.com/blog">BLOG</a>
<a href="http://asdas.com/blog">   blogging   </a>

结果:http://asdas.com/blog

这项工作正常,除非链接中有更多的html标签...

<a class="asdadasd" href="http://asdas.com/blog" id="asdasd">this is our blog</a>

结果:http://asdas.com/blog" id="asdasd

这就是我所拥有的

(?i)<a.+href="(.*)".*>.*?blog.*?</a>

2 个答案:

答案 0 :(得分:1)

您需要使用?(.*)懒惰。否则,.*会继续抓住所有内容,直到最终结束"

试试这个:

(?i)<a.+href="(.*?)".*>.*?blog.*?</a>

我所做的就是将(.*)更改为(.*?)

答案 1 :(得分:0)

单独使用RegEx很头疼。永远不要使用RegEx解析HTML文档。使用DOMParser()执行此操作:

&#13;
&#13;
var html = `<a href="http://asdas.com/blog">this is our blog</a>
<a href="http://asdas.com/blog">BLOG</a>
<a href="http://asdas.com/blog">   test   </a>`;

var doc = (new DOMParser()).parseFromString(html, 'text/html')
var aTags = doc.documentElement.getElementsByTagName('a')

Array.prototype.slice.call(aTags).forEach(function(a) {
   if(a.innerText.match(/blog/i))
     console.log(a.href)
});
&#13;
&#13;
&#13;