使用Perl,我试图解析一堆XML文件,并尝试在XML中查找任何形式的URL并打印它.我的正则表达式似乎不起作用,它没有返回任何匹配.我错过了什么?
sub findURL{
local($inputLine, $outText);
$inputLine = $_[1];
while (length($inputLine) > 0)
{
if ($inputLine =~ /^(((http|https|ftp):\/\/)?([[a-zA-Z0-9]\-\.])+(\.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]\/+=%&_\.~?\-]*))*$/ )
{
$outText .= $&;
$inputLine = $';
}
else
{
$inputLine = "";
$outText .= "";
}
}
return $outText;
}
Run Code Online (Sandbox Code Playgroud)
Анд*_*нко 12
使用Regexp :: Common
use Regexp::Common qw /URI/;
while (<>) {
/$RE{URI}{HTTP}/ and print "Contains an HTTP URI.\n";
}
Run Code Online (Sandbox Code Playgroud)
你的代码有七种不同的错误:
local 可能不应该以那种方式使用,你可能想要 my$&,$'和$`不应该使用的变量(使用捕捉代替)$inputLine = $_[1]; 抓住函数的第二个参数(第一个是什么?)/g正则表达式修饰符,而不是滚动自己的多个匹配代码(?:)用于分组,而不是())下面是我如何写代码,如果我不在乎我会抓住我不应该的东西,可能会错过我想要的东西(因为正则表达式不够聪明,无法解析XML).请注意如何抓取评论中的URL.
#!/usr/bin/perl
use strict;
use warnings;
use Regexp::Common qw/URI/;
sub find_urls {
my $text = shift;
return $text =~ /$RE{URI}{-keep}/g;
}
my $xml = do { local $/; <DATA> };
for my $url (find_urls($xml)) {
print "$url\n";
}
__DATA__
<root>
this is some text
and a URL: http://foo.com/foo.html
this isn't a URL http:notgrabbed.com
<img src="http://example.com/img.jpg" />
<!-- oops, shouldn't grab this one: ftp://bar.com/donotgrab -->
</root>
Run Code Online (Sandbox Code Playgroud)