The first problem is that character classes are constructed when the regexp is compiled, and do not change during the matching process. Because of that the special syntax for backreferences in regexps does not extend inside the character class, so as tye mentioned the '\2' is actually treated as ASCII character 2.
You could circumvent that by getting clever with deferred evals (which lets you create new regexps to be compiled while matching), but you don't want to do that - the negative lookahead is definitely the way to go.
All of the extended features in the regexp engine are of the form (?...), to avoid clashing with any previously valid syntax; the ($!\2) in your example actually interpolated the $! error variable into your regexp - presumably the empty string.
So a correct solution would look something like:
.. and to the extended example:m{ (\w) \1 (?! \1) (\w) }x;
m{ (\w) \1 (?! \1) (\w) (?! \1 | \2) (\w) \3 \3 \3 \1 (?! \1 | \2 | \3) (\w) }x;
This gives you something nice and regular - it would be quite easy to write code to generate the above from the example string. Here's how it might work:
my $s = 'AABCCCCAD'; our $DEBUG = 1; print +($s =~ mkre($s)) ? "ok\n" : "fail\n"; sub mkre { my $s = shift; my $index = 0; my(%seen, @elems); for (split //, $s) { if ($seen{$_}) { push @elems, "\\$seen{$_}"; } else { push @elems, sprintf '(?! %s)', join ' | ', map "\\$_", 1 .. $in +dex if $index; $seen{$_} = ++$index; push @elems, '(\\w)'; } } my $re = join ' ', @elems; warn "$s: $re\n" if $DEBUG; qr/$re/x; }
Hugo
In reply to Re: Backreferences in negated character classes
by hv
in thread Backreferences in negated character classes
by bobf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |