我想创建一个perl代码来提取括号中的内容并将其移植到变量中。 “(05-NW)HPLaserjet”应成为“05-NW” 像这样:
我将如何做到这一点?
答案 0 :(得分:3)
这是正则表达式的工作。看起来令人困惑,因为parens在正则表达式中用作元字符,并且也是示例中模式的一部分,由反斜杠转义。
C:\temp $ echo (05-NW)HPLaserjet | perl -nlwe "print for m/\(([^)]+)\)/g"
匹配开始线,开始捕捉组,匹配一个或多个不是结束线的角色,关闭捕获组,匹配关闭线。
答案 1 :(得分:2)
您可以使用正则表达式(请参阅perlretut)来匹配和捕获值。通过分配列表,您可以将捕获放入命名变量中。全局变量$1
,$2
等也用于捕获组,因此如果您愿意,可以使用它而不是列表赋值。
use strict;
use warnings;
while (<>) # read every line
{
my ($printer_code) = m/
\( # Match literal opening parenthesis
([^\)]*) # Capture group (printer_code): Match characters which aren't right parenthesis, zero or more times
\)/x; # Match literal closing parenthesis
# The 'x' modifier allows you to add whitespace and comments to regex for clarity.
# If you use it, make sure you use '\ ' (or '\s', etc.) for actual literal whitespace matching!
}
__DATA__
(05-NW)HPLaserjet
答案 2 :(得分:1)
use warnings;
use strict;
my $s = '(05-NW)HPLaserjet';
my ($v) = $s =~ /\((.*)\)/; # Grab everything between parens (including other parens)
$v =~ s/\s//g; # Remove all whitespace
print "$v\n";
__END__
05-NW