假設我有2個正則表達式[\d\d]
和[a-zA-Z][a-zA-Z]
我想檢查一個字符串是否有任何數量和順序的模式,只有那些用逗號分隔的模式我怎麼能這樣做用perl?與perl正則表達式發生2模式匹配
例如字符串
ex,xy,gf,55,66-> match
例如字符串
22,24,25,56,ff ->match
例如字符串
2FF,24,25,56,ff -> not match
假設我有2個正則表達式[\d\d]
和[a-zA-Z][a-zA-Z]
我想檢查一個字符串是否有任何數量和順序的模式,只有那些用逗號分隔的模式我怎麼能這樣做用perl?與perl正則表達式發生2模式匹配
例如字符串ex,xy,gf,55,66-> match
例如字符串22,24,25,56,ff ->match
例如字符串2FF,24,25,56,ff -> not match
緊接在'\ d \ d'附近的括號是多餘的,否則爲+1。 –
#!/usr/bin/perl
use warnings;
use strict;
my $pattern1 = '\d';
my $pattern2 = '[a-zA-Z]';
my $string = ('ex,xy,gf,55,66');
my $warning = 0;
my @split = split(/,/, $string);
foreach (@split){
unless (($_ =~ /^$pattern1{2}$/) or ($_ =~ /^$pattern2{2}$/)) {
$warning++;
}
}
print "$string -> match\n" if ($warning == 0);
print "$string -> no match" if ($warning != 0);
輸出:
ex,xy,gf,55,66 -> match
同樣的代碼,不同的字符串:
my $string = ('22,2f,ex,xy,gf,2FF');
輸出:
22,2f,ex,xy,gf,2FF -> no match
下面是一個使用/^(?:[a-z]{2},?|\d\d,?)+$/i
一個選項:
use strict;
use warnings;
while (<DATA>) {
chomp;
my @elems = split /,/;
my @match = grep /^(?:\d{2}|[a-z]{2})$/i, @elems;
print "$_ -> ", (@elems == @match ? '' : 'not '), "match\n"
}
__DATA__
ex,xy,gf,55,66
22,24,25,56,ff
2FF,24,25,56,ff
輸出:
ex,xy,gf,55,66 -> match
22,24,25,56,ff -> match
2FF,24,25,56,ff -> not match
希望這有助於!
您可以使用此:
^((?>[a-z]{2}|[0-9]{2})(?>,(?1)|$))
或者這個:
^(?>(?>[a-z]{2}|[0-9]{2})(?>,|$))+$
在Perl中玩弄這個之後,我想出了這個。
我測試了Perl中發佈的所有答案。這些問題來自於嘗試匹配非常大的字符串
。主要是> 256 K. Perl似乎找不到匹配項,其中
的尺寸較小,但它確實如此。也許它是我沒有使用的設置,我不知道。
Casimir的遞歸正則表達式是個例外,它需要一分鐘的時間才能匹配一個3兆bufffer。
因此,對於咧嘴笑,我把一個正則表達式匹配所允許的負數。
15兆緩衝區在我的機器上最多需要10秒,具體取決於故障(匹配)
是什麼時間,或者如果通過,則爲10秒。值得注意的是,沒有捕獲信息的積累,也許這就是爲什麼它可以處理大型緩衝區。
$test = "ex,xy,gt,55,66,";
for (0 .. 19) { $test .= $test; }
$test .= "3a3";
print "\nlength = ", length($test), "\n------------\n";
if ($test =~ m/
# \d(?:[a-z]|\d{2})|[a-z](?:\d|[a-z]{2})|[^a-z\d,]|,(?:.?,|$)|^,
\d
(?: [a-z] | \d{2})
|
[a-z]
(?: \d | [a-z]{2})
|
[^a-z\d,]
|
,
(?: .? , | $)
|
^,
/xg)
{ print "Found error at pos = ", pos($test), "\n"; }
else
{ print "Passed test!\n"; }
__END__
Output >>
length = 15728643
------------
Found error at pos = 15728642
'2f'是否爲有效匹配? –
'\ w'已經包含數字'\ d',這意味着你也可以得到字母和數字的混合匹配,比如上面提到的那個'2f'。您需要決定是否有效匹配。另外,'[\ d \ d]'是一個冗餘表達式,簡化爲'\ d'。 – TLP
沒有它沒有一個有效的匹配只有提示,我的意思是我修改了問題 – smith