使用Perl,我如何使用正则表达式来获取带有随机HTML的字符串,其中包含一个带有锚点的HTML链接,如下所示:
<a href="http://example.com" target="_blank">Whatever Example</a>
它只留下那个并摆脱其他一切?无论href属性中的内容是&lt; a,如title=
,还是style=
,还是其他什么。
它离开了锚:&#34;无论如何&#34;和&lt; / a&gt;?
答案 0 :(得分:2)
您可以利用HTML::TokeParser::Simple:
等流解析器#!/usr/bin/env perl
use strict;
use warnings;
use HTML::TokeParser::Simple;
my $html = <<EO_HTML;
Using Perl, how can I use a regex to take a string that has random HTML in it
with one HTML link with anchor, like this:
<a href="http://example.com" target="_blank">Whatever <i>Interesting</i> Example</a>
and it leave ONLY that and get rid of everything else? No matter what
was inside the href attribute with the <a, like title=, or style=, or
whatever. and it leave the anchor: "Whatever Example" and the </a>?
EO_HTML
my $parser = HTML::TokeParser::Simple->new(string => $html);
while (my $tag = $parser->get_tag('a')) {
print $tag->as_is, $parser->get_text('/a'), "</a>\n";
}
输出:
$ ./whatever.pl <a href="http://example.com" target="_blank">Whatever Interesting Example</a>
答案 1 :(得分:1)
如果您需要一个简单的正则表达式解决方案,那么天真的方法可能是:
my @anchors = $text =~ m@(<a[^>]*?>.*?</a>)@gsi;
但是,正如@ dan1111所提到的,正则表达式不是解析various reasons的HTML的正确工具。
如果您需要可靠的解决方案,请查找HTML parser module。