in reply to regex is not working as I intended
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 \.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: regex is not working as I intended
by ikegami (Patriarch) on Jan 19, 2018 at 05:20 UTC | |
by fireblood (Scribe) on Jan 22, 2018 at 19:11 UTC | |
by AnomalousMonk (Archbishop) on Jan 23, 2018 at 01:05 UTC | |
by GrandFather (Saint) on Jan 22, 2018 at 22:38 UTC | |
by ikegami (Patriarch) on Jan 22, 2018 at 23:15 UTC |