如果$ 1 <$ 2,我怎样才能使我的Perl正则表达式匹配?

Zai*_*aid 6 regex perl

我不能完全开始工作的部分是有条件的,因为它总是失败:

use Test::More tests => 2;

my $regex = qr/(\d+),(\d+)
               (?(?{\g1<\g2})(*FAIL))
              /x ;

  like( "(23,36)", $regex, 'should match'     );
unlike( "(36,23)", $regex, 'should not match' );
Run Code Online (Sandbox Code Playgroud)

产量

not ok 1 - should match
#   Failed test 'should match'
#   at - line 7.
#                   '(23,36)'
#     doesn't match '(?^x:(\d+),(\d+)
#                    (?(?{\g1<\g2})(*FAIL))
#                   )'
ok 2 - should not match
# Looks like you failed 1 test of 2.
Run Code Online (Sandbox Code Playgroud)

Mil*_*ler 11

您的代码需要以下修复:

  • 使用实验代码块中的$1$2变量(?{ }).
  • 需要反转您的测试以匹配您想要失败的.
  • 您需要阻止回溯,如果代码块指示失败,您不希望它匹配将传递的子字符串,例如在第二次测试中6小于23.有两种方法可以防止这种情况:
    • 添加单词边界,使正则表达式无法匹配部分数字.
    • 使用(*SKIP)控件动词可以明确地防止回溯.

代码:

use strict;
use warnings;

use Test::More tests => 2;

my $regex = qr/(\d+),(\d+)
               (?(?{$1 > $2})(*SKIP)(*FAIL))
              /x ;

  like( "(23,36)", $regex, 'should match'     );
unlike( "(36,23)", $regex, 'should not match' );
Run Code Online (Sandbox Code Playgroud)

输出:

1..2
ok 1 - should match
ok 2 - should not match
Run Code Online (Sandbox Code Playgroud)