perl中的模式匹配

perl中的模式匹配,perl,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 ab

我想解析文件中的一些信息

文件中的信息:

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
中?我想我的regexp缺少一些东西。你有什么建议吗?

不太好,但接下来:

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
$b
。它们是按排序使用的,会使您感到困惑

尝试:

while(我的$line=){
chomp$行;
如果($line=~m{\A(\w+)u([^\ u]*\ d[^\u]*)\ z}msx){
my$first=$1;
我的$second=2美元;
打印“\$a=$first和\$b=$second\n”;
}否则{
打印“\$a=$行和\$b=\”原件\“\n”;
}
}
__资料__
丽塔·自行车屋·沙9
丽塔·比克·豪斯酒店

如果您确定所需的模式将始终与“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";
    }
}
打开文件,“filename.txt”或die$!;
我的@data=;
close();
#my$line=“丽塔·自行车·房子·沙9”;
foreach$行(@data)
{
chomp($line);
如果($line=~m/(.*)([a-zA-Z]+[0-9]+)?$/)
{
$a=$1;
$b=$3?$3:“原件”;
}
}

$name=@
是一种代码气味。您可能是说,
\w
也匹配
\u
(下划线),因此您需要更精确的匹配规则。对此表示抱歉。是的,它是($name)=@;我厌倦了将模式匹配作为/\w\uw\uw([\w\d]+)/。但是,它不起作用。在模式匹配中有什么建议吗?谢谢
\w
只匹配一个字母。您需要
\w+
来匹配一个或多个字母(一个单词)。但是
\w
也与
\u
匹配,所以如果这是你的意思,你最好使用
[a-z]
。谢谢你的输入,但是我收到一个错误,说“my$b=pop@parts if$parts[$#parts]=~/\d/;”我不能使用5.014;有什么建议为什么不分析行“my$b=pop@parts if$parts[$#parts]=~/\d/;”
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
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";
    }
}