對於字符串「aa \ nbb \ ncc」,我希望匹配從最後一個字母到第一個換行符(「a」)到多行字符串,並預計
"aa\nbb\ncc" =~ qr/(. $ .+)/xms
匹配a\nbb\ncc
和
"aa\nbb\ncc\n" =~ qr/(. $ .+)/xms
比賽a\nbb\ncc\n
。
但我沒有匹配"aa\nbb\ncc" =~ qr/(. $ .+)/xms
和匹配c\n
爲"aa\nbb\ncc" =~ qr/(. $ .+)/xms
。
使用qr/(. $ ..+)/xms
我得到了預期的結果(請參閱示例代碼)。
Perl version 5.14.2。
任何人都可以解釋這種行爲嗎?
的perldoc perlre:
m Treat string as multiple lines. That is, change "^" and "$"
from matching the start or end of the string to matching the start
or end of any line anywhere within the string.
s Treat string as single line. That is, change "." to match any character
whatsoever, even a newline, which normally it would not match.
Used together, as "/ms", they let the "." match any character whatsoever,
while still allowing "^" and "$" to match, respectively, just after and
just before ewlines within the string.
\z Match only at end of string
運行下面的示例代碼:
#!/usr/bin/env perl
use strict;
use warnings;
print "Multiline string : ", '"aa\nbb\ncc"', "\n\n";
my $str = "aa\nbb\ncc";
print_match($str, qr/(. $)/xms); # matches "a"
print_match($str, qr/(. $ .)/xms); # matches "a\n"
print_match($str, qr/(. $ ..)/xms); # matches "a\nb"
print_match($str, qr/(. $ ..+)/xms); # matches "a\nbb\ncc"
print_match($str, qr/(. $ .+)/xms); # NO MATCH ! Why ???
print_match($str, qr/(. $ .+ \z)/xms); # NO MATCH ! Why ???
print "\nMultiline string now with terminating newline : ", '"aa\nbb\ncc\n"', "\n\n";
$str = "aa\nbb\ncc\n";
print_match($str, qr/(. $)/xms); # matches "a"
print_match($str, qr/(. $ .)/xms); # matches "a\n"
print_match($str, qr/(. $ ..)/xms); # matches "a\nb"
print_match($str, qr/(. $ ..+)/xms); # matches "a\nbb\ncc\n"
print_match($str, qr/(. $ .+)/xms); # MATCHES "c\n" ! Why ???
print_match($str, qr/(. $ .+ \z)/xms); # MATCHES "c\n" ! Why ???
sub print_match {
my ($str, $regex) = @_;
$str =~ $regex;
if ($1) {
printf "--> %-20s matched : >%s< \n", $regex, $1;
}
else {
printf "--> %-20s : no match !\n", $regex;
}
}
輸出爲:
Multiline string : "aa\nbb\ncc"
--> (?^msx:(. $)) matched : >a<
--> (?^msx:(. $ .)) matched : >a
<
--> (?^msx:(. $ ..)) matched : >a
b<
--> (?^msx:(. $ ..+)) matched : >a
bb
cc<
--> (?^msx:(. $ .+)) : no match !
Multiline string now with terminating newline : "aa\nbb\ncc\n"
--> (?^msx:(. $)) matched : >a<
--> (?^msx:(. $ .)) matched : >a
<
--> (?^msx:(. $ ..)) matched : >a
b<
--> (?^msx:(. $ ..+)) matched : >a
bb
cc
<
--> (?^msx:(. $ .+)) matched : >c
<
這看起來像是Perl中的一個錯誤。好找!相關地:''a \ nb「'匹配'm/a $ ... \ z/ms'而不是'm/a $ .. \ z/ms'; *但是*,當我在圓點周圍添加括號以試圖弄清楚發生了什麼時,它突然匹配'm/a $(。)(。)\ z/ms'而不是'm/a $(。)( 。)(。)\ Z/ms'。 – ruakh 2012-07-10 11:44:36
頗爲奇怪。同樣在perl 5.12.2。 – katastrophos 2012-07-10 12:15:52