【问题标题】:Perl : Split the string into desirable partsPerl:将字符串拆分为所需的部分
【发布时间】:2015-06-18 10:15:41
【问题描述】:

我是 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";

如何做到这一点?

【问题讨论】:

  • 每个部分的末尾是否有换行符?
  • @Jens 没有换行符,它是一个带有空格的连续字符串。
  • 有什么吸引眼球的东西或者这背后的逻辑是什么。

标签: arrays regex string perl split


【解决方案1】:

只根据在一个或多个非空格字符之前存在的空格后跟一个冒号,然后再跟一个空格来拆分。所以这与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

【讨论】:

  • 我不明白你的正则表达式为什么你使用/\s+(?=[^:\s]+:\s+)/ 我用这个/\s+(?=[\w]+:\s+)/ 而不是那个。在这种情况下,[^:\s] 是什么意思?否定是如何工作的?
  • 如果关键部分包含除a-zA-Z0-9_ 以外的字符,那么您的正则表达式将不起作用。所以我使用了[^\s:],它匹配一个字符,但不匹配空格或冒号。 [^:\s]+ 一次或多次。
猜你喜欢
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 2012-07-30
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
相关资源
最近更新 更多