1

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

文件中的信息:

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. 

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

4

3 回答 3

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
于 2013-07-08T21:22:24.117 回答
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",
于 2013-07-08T19:48:29.423 回答
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";
    }
}
于 2013-07-09T10:08:16.403 回答