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'} :

In reply to Regex alternatives not behaving as expected by ibm1620

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.