Perl:将字符串拆分为所需的部分

时间:2015-04-13 07:07:17

标签: arrays regex string perl split

我是perl的新手并尝试将此字符串拆分为4个部分并将其存储在@parts数组中。

$string = " Google Inc. 1600 Amphitheatre Parkway Mountain View, CA 94043 United States - Map Phone: 650-253-0000 Fax: 650-253-0001 Website: http://www.google.com ";

使@parts数组成为

$part[0]= "Google Inc. 1600 Amphitheatre Parkway Mountain View, CA 94043 United States - Map" ;
$part[1]= "Phone: 650-253-0000 ";
$part[2]= "Fax: 650-253-0001 ";
$part[3]= "Website: http://www.google.com";

如何实现这一目标?

1 个答案:

答案 0 :(得分:4)

根据在一个或多个非空格字符之后存在的空格进行拆分,然后是冒号,后面跟一个空格。因此,这与http:之前的空格不匹配,因为http:后面没有空格。

my $string = "Google Inc. 1600 Amphitheatre Parkway Mountain View, CA 94043 United States - Map Phone: 650-253-0000 Fax: 650-253-0001 Website: http://www.google.com ";
my @abc = split /\s+(?=[^:\s]+:\s+)/, $string;
print $_, "\n" for @abc;

<强>输出:

Google Inc. 1600 Amphitheatre Parkway Mountain View, CA 94043 United States - Map
Phone: 650-253-0000
Fax: 650-253-0001
Website: http://www.google.com