Regex 如何获取字符串中正则表达式的所有匹配项?
如何使用Regex 如何获取字符串中正则表达式的所有匹配项?,regex,perl,curl,Regex,Perl,Curl,如何使用curl获取任何html标记的内容? 在以下脚本中获取例如h1内容: #!/usr/bin/perl use strict; use warnings; my $page = `curl www.yahoo.com`; print "Page: \n"; sleep(5); #print "$page \n"; if ($page =~ m/<h1\s*>(.*)<\/h1\s*>/ig){ print "$1
curl
获取任何html标记的内容?
在以下脚本中获取例如h1
内容:
#!/usr/bin/perl
use strict;
use warnings;
my $page = `curl www.yahoo.com`;
print "Page: \n";
sleep(5);
#print "$page \n";
if ($page =~ m/<h1\s*>(.*)<\/h1\s*>/ig){
print "$1 \n";
}
#/usr/bin/perl
严格使用;
使用警告;
my$page=`curl www.yahoo.com`;
打印“第页:\n”;
睡眠(5);
#打印“$page\n”;
如果($page=~m/(.*)/ig){
打印“$1\n”;
}
我只有一场比赛。如何获取所有匹配项?您可以像这样获取所有匹配项:
my @matches = $page =~ /<h1\b[^>]*>(.*?)<\/h1>/ig;
print "@matches\n";
my@matches=$page=~/]*>(.*)/ig;
打印“@matches\n”;
(但请注意,在yahoo.com上,只有一个h1标签)您可以获得如下所有匹配:
my @matches = $page =~ /<h1\b[^>]*>(.*?)<\/h1>/ig;
print "@matches\n";
my@matches=$page=~/]*>(.*)/ig;
打印“@matches\n”;
(但请注意,在yahoo.com上,只有一个h1标记)使用while循环,而不是if:
while ($page =~ m/<h1\s*>(.*)<\/h1\s*>/ig) {
print "$1 \n";
}
while($page=~m/(.*)/ig){
打印“$1\n”;
}
如果,则使用while循环代替:
while ($page =~ m/<h1\s*>(.*)<\/h1\s*>/ig) {
print "$1 \n";
}
while($page=~m/(.*)/ig){
打印“$1\n”;
}
。幸运的是,周围有很多解析器。我特别喜欢魔咒组曲:
use strict; use warnings;
use feature 'say';
use Mojo;
my $ua = Mojo::UserAgent->new(max_redirects => 5); # redirects defaults to zero
for my $h3 ($ua->get('www.stackoverflow.com')->res->dom('h3')->each) { # use CSS selectors
say $h3->all_text;
}
use strict; use warnings;
use feature 'say';
use Mojo;
my $ua = Mojo::UserAgent->new(max_redirects => 5); # redirects defaults to zero
for my $h3 ($ua->get('www.stackoverflow.com')->res->dom('h3')->each) { # use CSS selectors
say $h3->all_text;
}