在perlretut中,它说您可以在正则表达式(不是替换的正确部分)中使用\g1
. 这在 5.14 中有所改变。因为我这里只有 5.12.2,所以我必须\1
改用。
因此,您的原始正则表达式稍作调整对我有用:
use strict; use warnings;
use 5.12.2;
use feature qw(say);
for (qw/ azalea baobab cyclic deadend teeeeeestest doesnotwork /) {
say if m/^([a-z])[^\1]+\1[^\1]+\1$/i;
}
用YAPE::Regex::Explain看它
use YAPE::Regex::Explain;
print YAPE::Regex::Explain->new(qr/^([a-z])[^\1]+\1[^\1]+\1$/i)->explain();
产量:
The regular expression:
(?i-msx:^([a-z])[^\1]+\1[^\1]+\1$)
matches as follows:
use YAPE::Regex::Explain;
print YAPE::Regex::Explain->new(qr/^([a-z])[^\1]+\1[^\1]+\1$/i)->explain();
NODE EXPLANATION
----------------------------------------------------------------------
(?i-msx: group, but do not capture (case-insensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
[a-z] any character of: 'a' to 'z'
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
[^\1]+ any character except: '\1' (1 or more
times (matching the most amount possible))
----------------------------------------------------------------------
\1 what was matched by capture \1
----------------------------------------------------------------------
[^\1]+ any character except: '\1' (1 or more
times (matching the most amount possible))
----------------------------------------------------------------------
\1 what was matched by capture \1
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
编辑:因此,您的单线是perl -e 'print if m/^([a-z])[^\1]+\1[^\1]+\1$/i'
.
另一方面,如果您尝试过perl -w -e 'print if m/(as)$1/'
,您会立即看到您的问题:
$ perl -w -e 'print if m/(a)$1/' asdf
Use of uninitialized value $1 in regexp compilation at -e line 1.
Use of uninitialized value $_ in pattern match (m//) at -e line 1.
我没有弄清楚为什么它匹配ololololo
。