2011-02-16 82 views
2

我有一堆字符串中有URL,我需要删除URL并用另一个替换它。我能想到的做到这一点的唯一方法是用split替换字符串中的URL - Perl

($start, $url, $end) = split(/:/); 

但我不认为这是去了解它的正确方法,因为如果该URL字符串的开始或结束它将无法正常工作。

任何想法不胜感激:)

+4

你能否提供几个例子,你要什么用字符串做? – Tim 2011-02-16 13:15:45

回答

1

URI::URL是你的朋友。

#!/usr/bin/perl 
use strict; 
use URI::Split qw(uri_split uri_join); 
my ($scheme, $auth, $path, $query, $frag) = uri_split($uri); 
my $uri = uri_join($scheme, $auth, $path, $query, $frag); 
+0

URI :: Split用于将URL拆分为其组成部分,而不是用于查找也包含其他文本的字符串中的URL。 – cjm 2011-02-16 20:51:39

2

已经建议URI::Find看起来是一个很好的选择。

或者,Regexp::Common可以提供合适的URL匹配的URL,例如:

use Regexp::Common qw(URI); 
my $string = "Some text, http://www.google.com/search?q=foo and http://www.twitter.com/"; 
$string =~ s{$RE{URI}}{http://stackoverflow.com/}g; 

上面将与http://stackoverflow.com/同时取代的URL,例如,