如何使用Perl在最后一组括号中提取子字符串?

kbr*_*n80 1 regex perl

我使用Perl来解析字符串中的大小.我可以用来完成这个的正则表达式是什么:

示例数据:Sleepwell Mattress(Twin)
Magic Nite(无翻盖设计)床垫(全XL)

结果:Twin Full XL

我知道我需要从字符串的末尾开始并解析第一组括号,但不知道该怎么做.

#!/usr/bin/perl

$file = 'input.csv';

open (F, $file) || die ("Could not open $file!");

while ($line = <F>)
{
  ($field1,$field2,$field3,$field4,$field5,$field6,$field7, $field8, $field9) = split ',', $line;
  if ( $field1 =~ /^.*\((.*)\)/ ) {
  print $1;
}


#print "$field1,$field2,$field3,$field4,$field5,$field6,$field7, $field8, $field9, $1\n";
}

close (F);
Run Code Online (Sandbox Code Playgroud)

没有得到任何结果.也许我做得不对.

Sin*_*nür 5

答案取决于您要查找的大小信息是否始终显示在字符串末尾的括号内.如果是这种情况,那么您的任务很简单:

#!/usr/bin/perl

use strict;
use warnings;

while (<DATA> ) {
    last unless /\S/;
    my ($size) = /\( ( [^)]+ ) \)$/x;
    print "$size\n";
}

__DATA__
Sleepwell Mattress (Twin)
Magic Nite (Flip Free design) Mattress (Full XL)
Run Code Online (Sandbox Code Playgroud)

输出:

C:\Temp> xxl
Twin
Full XL

请注意,您发布的代码可以更好地编写为:

#!/usr/bin/perl

use strict;
use warnings;

my ($input_file) = @ARGV;

open my $input, '<', $input_file
    or die "Could not open '$input_file': $!";

while (my $line = <$input>) {
    chomp $line;
    my @fields = split /,/, $line;
    if ($field[0] =~ /\( ( [^)]+ ) \)$/x ) {
        print $1;
    }
    print join('|', @fields), "\n";
}

close $input;
Run Code Online (Sandbox Code Playgroud)

此外,您应该考虑使用Text :: xSVText :: CSV_XS来处理CSV文件.