注意:不要使用正则表达式来解析 HTML。
第一个选项是使用HTML::TreeBuilder完成的,它是许多可供使用的 HTML 解析器之一。您可以访问上面提供的链接并阅读文档并查看给出的示例。
use strict;
use warnings;
use HTML::TreeBuilder;
my $str
= "<ul>"
. "<li>hello</li>"
. "<li>there</li>"
. "<li>everyone</li>"
. "</ul>"
;
# Now create a new tree to parse the HTML from String $str
my $tr = HTML::TreeBuilder->new_from_content($str);
# And now find all <li> tags and create an array with the values.
my @lists =
map { $_->content_list }
$tr->find_by_tag_name('li');
# And loop through the array returning our values.
foreach my $val (@lists) {
print $val, "\n";
}
如果您决定在这里使用正则表达式(我不推荐)。你可以做类似..
my $str
= "<ul>"
. "<li>hello</li>"
. "<li>there</li>"
. "<li>everyone</li>"
. "</ul>"
;
my @matches;
while ($str =~/(?<=<li>)(.*?)(?=<\/li>)/g) {
push @matches, $1;
}
foreach my $m (@matches) {
print $m, "\n";
}
输出:
hello
there
everyone