2013-07-08 113 views
1

我想解析文件中的一些信息。在該文件中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中存儲「Rita_bike_house」,在$b中存儲「Sha9」?我認爲我的正則表達式缺少某些東西。你能提出什麼建議嗎?

+2

'$ name = @ _'是一種代碼味道。您可能的意思是['($ name)= @ _'](http://stackoverflow.com/q/10031455/168657)。 – mob

+0

'\ w'也匹配'_'(下劃線),所以你需要更精確的匹配規則。 – jm666

+0

對不起。是的,它是($ name)= @_; – user2498830

回答

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", 
+0

感謝您的輸入,但我得到一個錯誤,說如果$ parts [$#parts] =〜/ \ d /;終止於「my $ b = pop @parts」我不能使用5.014; – user2498830

+0

任何建議爲什麼它不解析行「my $ b = pop @parts if $ parts [$#parts] =〜/ \ d /;」 – user2498830

+0

@ user2498830請參閱編輯.. – jm666

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 
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"; 
    } 
}