QRegExp。抓住所有链接

时间:2014-05-08 16:33:40

标签: html regex qt qregexp

我编写正则表达式以从html中获取所有引用链接

QRegExp bodylinksrx("(<a\\s+href\\s*=\\s*[^<>]*\\s*>[^<>]*</a>)");
QStringList bodylinks;
pos = 0;
while ((pos = bodylinksrx.indexIn(htmlcode, pos)) != -1)
{
    bodylinks << bodylinksrx.cap(1);
    pos += bodylinksrx.matchedLength();
}

我收到列表结果:

("<a href="http://somehref" class="someclass">href text...</a>", "<a href="http://somehref" class="someclass">href text...</a>", ......")

但我需要只有"http://somehref" "href text..." "http://somehref" "href text..." ....

的接收列表

1 个答案:

答案 0 :(得分:1)

如果您确定自己知道自己在做什么,并且肯定知道自己想要这样做,那么首先请你read this?尝试为你的锚标签使用lookahead和lookbehind断言。

((?<=<a\\s+href\\s*=\\s*[^<>]*\\s*>)[^<>]*(?=</a>))

编辑:遗憾的是,这不会起作用(至少在qt4.8中)作为后瞻性断言are not supported。您可以遍历创建的列表并将所需的位与:

匹配
[^<>]*(?=<)

并使用它,或者使用captured texts function来提取你想要用括号括起来的部分,如下所示:

<a\\s+href\\s*=\\s*[^<>]*\\s*>([^<>]*)</a>
相关问题