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

I'm testing for apostrophes at the beginning (regex #1) and end (regex #2) of words. These two regexes behave as I expected, but when I combine them as alternatives in a single regex (regex #3), it completely fails to match.

(I'm not really looking for better ways to look for apostrophes, I just want to understand why if A is true, "A or B" isn't true.)

perl 5.34.0

#!/usr/bin/env perl use 5.010; use warnings; use strict; my @frags = qw{ "'frags'" "'frags frags'. frag's. frags. frags' }; for my $frag (@frags) { print "{$frag} : "; if ($frag =~ /\W'\w/) { #1 print 'matched by first regex. '; } if ($frag =~ /\w'\W/) { #2 print 'matched by second regex. '; } if ($frag =~ /\W'\w | \w'\W/) { #3 print 'matched by third regex. '; } say ''; }
Result:
{"'frags'"} : matched by first regex. matched by second regex. {"'frags} : matched by first regex. {frags'.} : matched by second regex. {frag's.} : {frags.} : {frags'} :

Replies are listed 'Best First'.
Re: Regex alternatives not behaving as expected
by ibm1620 (Hermit) on Mar 12, 2022 at 03:33 UTC
    never mind. forgot the /x.