这是一种可能的方法(但我强烈 建议不要为此使用正则表达式):
my $good_text = "some text>http://www.hulu.com/watch/sdfsdf";
my $bad_text = "some text>http://www.hulu.com/watch/";
$good_text =~
s!(^|\s|\>)((?:http|https)://www.hulu.com/watch/([a-z0-9/-]*))!$1\[video\]@{[($3) ? $2 : "No video"]}\[\/video\]!isg;
$bad_text =~
s!(^|\s|\>)((?:http|https)://www.hulu.com/watch/([a-z0-9/-]*))!$1\[video\]@{[($3) ? $2 : "No video"]}\[\/video\]!isg;
print "Good '$good_text'\n";
print "Bad '$bad_text'\n";
$good_text = "some text>http://www.hulu.com/watch/sdfsdf";
$bad_text = "some text>http://www.hulu.com/watch/";
#below is the right way for such things -- using /e switch and function call
$good_text =~
s!(^|\s|\>)((?:http|https)://www.hulu.com/watch/([a-z0-9/-]*))!check_result($1, $2, $3)!isge;
$bad_text =~
s!(^|\s|\>)((?:http|https)://www.hulu.com/watch/([a-z0-9/-]*))!check_result($1, $2, $3)!isge;
print "Good '$good_text'\n";
print "Bad '$bad_text'\n";
sub check_result {
my ($text, $url, $id) = @_;
if ($id) {
return $text . "[video]" . $url . $id . "[/video]";
}
else {
return $text . "[video]No video[/video]";
}
}