【问题标题】:Perl Regex Variable Replacement printing 1 instead of desired extractionPerl 正则表达式变量替换打印 1 而不是所需的提取
【发布时间】:2021-01-08 04:57:50
【问题描述】:

案例 1:

year$ = ($whole =~ /\d{4}/);
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 =~ /\d{4}/;
$year =  ($whole);
print ("The year is $year for now!";)

输出:现在是 2020 年!暂时!

有没有办法将 $year 变量设为 2020 年?

【问题讨论】:

    标签: regex perl variables perl5.8


    【解决方案1】:

    使用括号捕获匹配项,并将其分配给$year,一步到位:

    use strict;
    use warnings;
    
    my $whole = "The year is 2020 for now!";
    my ( $year ) =  $whole =~ /(\d{4})/;
    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/(\d{4})/;
      $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 =~ /(\d{4})/);
      
      print $year."\n";
      print "The year is $year for now!";
      

      输出:

      2020
      The year is 2020 for now!
      

      【讨论】:

      • 这比 PYPL 的答案要好,因为它不会在没有确认匹配发生的情况下使用 $1,但请参阅 Timur 的答案以获得更简洁的方法来做同样的事情。
      猜你喜欢
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 2010-12-19
      相关资源
      最近更新 更多