[英]Pattern Matching in perl
I want to parse some information from the file. 我想解析文件中的一些信息。
Information in the file: 文件中的信息:
Rita_bike_house_Sha9
Rita_bike_house
I want to have output like dis 我想输出像dis
$a = Rita_bike_house and $b = Sha9,
$a = Rita_bike_house and $b = "original"
In order to get that I have used the below code: 为了得到我使用了下面的代码:
$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.
Is there any way where I can store "Rita_bike_house" in $a
and "Sha9" in $b
? 有什么方法可以在$a
存储“ Rita_bike_house”而在$b
存储“ Sha9”? I think my regexp is missing with something. 我认为我的正则表达式缺少某些东西。 Can you suggest anything? 你能建议什么吗?
Please don't use the variables $a
and $b
in your code. 请不要在代码中使用变量$a
和$b
。 There are used by sort and will confuse you. 有按排序使用,会使您感到困惑。
Try: 尝试:
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
Not very nice, but the next: 不是很好,但是下一个:
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
prints: 打印:
$a = Rita_bike_house and $b = Sha9,
$a = Rita_bike_house and $b = "original",
If you are sure that the pattern which is required will always be similar to 'Sha9' and also it will appear at the end then just do a greedy matching.... 如果您确定所需的模式始终与“ 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";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.