misterperl has asked for the wisdom of the Perl Monks concerning the following question:

I tried to ask this yesterday but didn't exactly propose it right. I want to match on:
"ABC" followed by ANYTHING (or NOTHING), EXCEPT exactly one case which is "ABCZ"
So "ABCDZABC" would match for example. I tried this:
/ABC[^Z]?.*$/
but that MATCHES on "ABCZ" . My current best and ugliest solution is:
my $x=0; $x++ if $match =~ /^ABC.*/ && $match !~ /^ABCZ$/;
Can do in one regex?

Replies are listed 'Best First'.
Re: sorry, didn't ask the right question about this regex yesterday (?!)
by tye (Sage) on Apr 21, 2016 at 14:47 UTC
      superdoc as Johnny used to say, "that is WILD and WACKY stuff!". I'm not sure how that works exactly but I'll try it in YAPE...

      As Ed used to tell Johnny- "YOU ARE CORRECT SIR!"...

      Thanks so much!

        Hello misterperl,

        I'm not sure how that works exactly...

        From “Look-Around Assertions” in perlre#Extended-Patterns:

        • (?!pattern)
          A zero-width negative look-ahead assertion. For example /foo(?!bar)/ matches any occurrence of "foo" that isn't followed by "bar".

        If you have access to the Camel Book, see also Chapter 5: Pattern Matching, section “Fancy Patterns,” subsection “Lookaround Assertions.”

        Hope that helps,

        Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: sorry, didn't ask the right question about this regex yesterday
by stevieb (Canon) on Apr 21, 2016 at 14:55 UTC

    Try the following, which uses a zero-width negative lookahead for the "Z":

    use warnings; use strict; while (<DATA>){ chomp; print "$_ matches\n" if /ABC(?!Z)/; } __DATA__ ABC ABCD ABCZ ABCZADF ABCDZADF AB XFC 123 AB1 ABC1 XXXABCZ2 ZZZABCDZ2 __END__ ABC matches ABCD matches ABCDZADF matches ABC1 matches ZZZABCDZ2 matches

    You didn't state where in a string this can match, so this'll match anywhere.