簡體   English   中英

如果$ 1 <$ 2,我怎樣才能使我的Perl正則表達式匹配?

[英]How can I get my Perl regex to match only if $1 < $2?

我不能完全開始工作的部分是有條件的,因為它總是失敗:

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' );

產量

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.

您的代碼需要以下修復:

  • 在實驗(?{ })代碼塊中使用$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' );

輸出:

1..2
ok 1 - should match
ok 2 - should not match

雖然米勒的解決方案完全符合您的要求 - 完全在正則表達式匹配中執行檢查 - 如果我沒有提出更合理的解決方案,我會失職:-)不要單獨使用正則表達式執行此操作!

use strict;
use warnings;

use Test::More tests => 2;

sub match {
    my $str = shift;

    if ($str =~ m/ (\d+) , (\d+) /x) {
        return $1 < $2;
    }

    return;
}

ok(match("(23,36)"), 'should match');
ok(!match("(36,23)"), 'should not match');

這更清晰,更簡單,而且可能更快!

1..2
ok 1 - should match
ok 2 - should not match

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM