[英]How can I get my Perl one-liner to show only the first regex match in the file?
[英]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
變量。 (*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.