Perl 正则表达式变量替换打印 1 而不是所需的提取
Posted
技术标签:
【中文标题】Perl 正则表达式变量替换打印 1 而不是所需的提取【英文标题】:Perl Regex Variable Replacement printing 1 instead of desired extraction 【发布时间】:2021-01-08 04:57:50 【问题描述】:案例 1:
year$ = ($whole =~ /\d4/);
print ("The year is $year for now!";)
输出:The year is The year is 1 for now!
案例 2:
$whole="The year is 2020 for now!";
$whole =~ /\d4/;
$year = ($whole);
print ("The year is $year for now!";)
输出:现在是 2020 年!暂时!
有没有办法将 $year 变量设为 2020 年?
【问题讨论】:
【参考方案1】:使用括号捕获匹配项,并将其分配给$year
,一步到位:
use strict;
use warnings;
my $whole = "The year is 2020 for now!";
my ( $year ) = $whole =~ /(\d4)/;
print "The year is $year for now!\n";
# Prints:
# The year is 2020 for now!
请注意,我将此添加到您的代码中,以启用捕获错误、拼写错误、不安全的结构等,从而阻止您显示的代码运行:
use strict;
use warnings;
【讨论】:
【参考方案2】:你必须将它捕获到一个组中
$whole="The year is 2020 for now!";
$whole =~ m/(\d4)/;
$year = $1;
print ("The year is $year for now!");
【讨论】:
理想情况下,你不想在没有确认匹配发生的情况下使用$1
(因为它会导致奇怪的、难以调试的结果),尤其是因为它很容易做到(如见帖木儿的回答)。【参考方案3】:
这是另一种捕获它的方法。这有点类似于@PYPL 的solution。
use strict;
use warnings;
my $whole = "The year is 2020 for now!";
my $year;
($year = $1) if($whole =~ /(\d4)/);
print $year."\n";
print "The year is $year for now!";
输出:
2020
The year is 2020 for now!
【讨论】:
这比 PYPL 的答案要好,因为它不会在没有确认匹配发生的情况下使用$1
,但请参阅 Timur 的答案以获得更简洁的方法来做同样的事情。以上是关于Perl 正则表达式变量替换打印 1 而不是所需的提取的主要内容,如果未能解决你的问题,请参考以下文章