I'm not sure why, but the last alternate ((.*)) seems to win in all cases when the other alternates use a look behind. However, things are much easier to understand if you look around less:

use strict; use warnings; my $regex = qr/(' ([^']*) ' | " ([^"]*) " | (.*))/x; do_test (qq~No quote~); do_test (qq~'Single quote'~); do_test (qq~"Double quote"~); sub do_test { my ($line) = @_; print "\n"; if ($line =~ $regex) { print "\$1 is $1.\n" if defined $1; print "\$2 is $2.\n" if defined $2; print "\$3 is $3.\n" if defined $3; print "\$4 is $4.\n" if defined $4; } else { print "No match.\n"; } }

Prints:

$1 is No quote. $4 is No quote. $1 is 'Single quote'. $2 is Single quote. $1 is "Double quote". $3 is Double quote.

Note too various other tidy ups in the code, especially avoiding calling subs with & (which doesn't do what you think) and excessive use of \.

Premature optimization is the root of all job security

In reply to Re: regex is not working as I intended by GrandFather
in thread regex is not working as I intended by fireblood

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.