perl中的模式匹配

时间:2013-07-08 19:18:04

标签: perl

我想从文件中解析一些信息。

文件中的信息:

Rita_bike_house_Sha9

Rita_bike_house

我希望输出像dis

$a = Rita_bike_house and $b = Sha9,

$a = Rita_bike_house and $b = "original"

为了得到我使用下面的代码:

$name = @_; # This @_ has all the information from the file that I have shown above. 

#For matching pattern Rita_bike_house_Sha9 
($a, $b) = $name =~  /\w\d+/; 

if ($a ne "" and $b ne "" ) { return ($a,$b) } 
# this statement doesnot work at all as its first condition 
# before the end is not satisified. 

有什么办法可以在$a$b的“Sha9”中存储“Rita_bike_house”吗?我认为我的正则表达式缺少某些东西。你能提出什么建议吗?

3 个答案:

答案 0 :(得分:2)

请不要在代码中使用变量$a$b。排序使用会让你感到困惑。

尝试:

while( my $line = <DATA> ){
  chomp $line;

  if( $line =~ m{ \A ( \w+ ) _ ( [^_]* \d [^_]* ) \z }msx ){
    my $first = $1;
    my $second = $2;
    print "\$a = $first and \$b = $second\n";
  }else{
    print "\$a = $line and \$b = \"original\"\n";
  }
}

__DATA__
Rita_bike_house_Sha9
Rita_bike_house

答案 1 :(得分:0)

不是很好,但下一个:

use strict;
use warnings;

while(<DATA>) {
    chomp;
    next if /^\s*$/;
    my @parts = split(/_/);
    my $b = pop @parts if $parts[$#parts] =~ /\d/;
    $b //= '"original"';
    my $a = join('_', @parts);
    print "\$a = $a and \$b = $b,\n";
}

__DATA__
Rita_bike_house_Sha9
Rita_bike_house

打印:

$a = Rita_bike_house and $b = Sha9,
$a = Rita_bike_house and $b = "original",

答案 2 :(得分:0)

如果你确定所需的模式总是与'Sha9'类似,并且它也会出现在最后,那么只需做一个贪婪的匹配....

open FILE, "filename.txt" or die $!;
my @data = <FILE>;
close(<FILE>);
#my $line = "Rita_bike_house_Sha9";
foreach $line (@data)
{
    chomp($line);
    if ($line =~ m/(.*?)(_([a-zA-Z]+[0-9]+))?$/)
    {
        $a = $1;
        $b = $3 ? $3 : "original";
    }
}