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:

m{ (\w) \1 (?! \1) (\w) }x;
.. and to the extended example:
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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.