Dear Monks and fellow followers,
I am unable to understand why my regex is not working the way I intended. I'm trying to write a regex that recognizes when a parameter value is enclosed in single or double quotes and pulls out the value that lies between the quotes, or when the value is not quoted it simply returns the value. Here is my code:
use strict;
my $regex = qr
/ # start of regex
( # start of capturing alternation
(?<=\') # positive lookbehind to a single quote
( # start of capture buffer 2
.*? # the value between the single quotes
) # end of capture buffer 2
(?>\') # positive lookahead to a single quote
| # or
(?<=\") # positive lookbehind to a double quote
( # start of capture buffer 3
.*? # the value between the double quotes
) # end of capture buffer 3
(?>\") # positive lookahead to a double quote
| # or
( # start of capture buffer 4
.* # any unquoted value
) # end of capture buffer 4
) # end of capturing alternation
/x # end of regex
;
&do_test (\"Now is the time"); # test with unquoted value
&do_test (\"'Now is the time'"); # test with single quoted value
&do_test (\'"Now is the time"'); # test with double quoted value
sub do_test
{
print "\n";
if (${$_[0]} =~ /$regex/)
{
print "\$1 is $1.\n";
print "\$2 is $2.\n";
print "\$3 is $3.\n";
print "\$4 is $4.\n";
}
else
{
print "No match.\n";
}
}
When I run this, I get:
$1 is Now is the time.
$2 is .
$3 is .
$4 is Now is the time.
$1 is 'Now is the time'.
$2 is .
$3 is .
$4 is 'Now is the time'.
$1 is "Now is the time".
$2 is .
$3 is .
$4 is "Now is the time".
Why are the first two alternatives not capturing quoted test strings?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|