【问题标题】:Perl: Conditional code execution inside regex patternPerl:正则表达式模式中的条件代码执行
【发布时间】:2017-01-12 10:03:20
【问题描述】:

我知道 Perl 5 中所谓的实验性(?{ ... }) 工具可以执行print 语句等代码,设置全局变量。

但是,我需要:

  1. 引用(?{ ... })块内的匹配字符串;和

  2. 根据它的值,执行一些任意代码

所需用途:

$input =~ m/ (foo) 
               (?{ if (defined (\1) { process(\1) } }) 
              bar
          /x;

注意:显然,实现相同效果 (TMTOWDI) 可能有无数种替代方法,但我现在只对上述风格感兴趣。因此,该帖子。

【问题讨论】:

  • 有什么问题?

标签: regex perl pattern-matching


【解决方案1】:

这是一个例子。

perldoc perlre:

$^N 包含与最近关闭的组(子匹配)匹配的任何内容

test_extended_re_code.pl

#!/usr/bin/env perl

use warnings;
use strict;

my @input = split /\n/, <<"END";
foo 123 bar
foo 456 bar
fo  789 bar
foo xyz bar
END

for my $input ( @input ) {
    $input =~ m/foo (\d+)(?{ process( $^N ) if $^N }) bar/;
}

sub process {
    my ($txt) = @_;
    print "Processing '$txt'\n";
}

输出

Processing '123'
Processing '456'

【讨论】:

  • 酷!我们是否还可以找出 foo 是否匹配但在 foo 周围没有分组/括号?
  • 是的,如果删除 foo 周围的括号,结果相同。更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多