I thought about using $1 and $2, but that doesn't seem to work.

I'm not saying that this is the preferred solution... but just for general interest: in those cases, you could use \1 and \2 instead, e.g.

my $s = q(var1='1' var2="2" var3="'3'" var4='"4"'); while ($s =~ m/(\w+)=(["'])(.*?)\2/g) { print "(using quote $2): $1 = $3\n"; }

Output:

(using quote '): var1 = 1 (using quote "): var2 = 2 (using quote "): var3 = '3' (using quote '): var4 = "4"

The ugly thing is that with input such as (incorrect according to your spec)

my $s = q(var1='1" var2="2');

it would extract the entire '1" var2="2' substring as one single quoted value...

You'd have to work around that by disallowing some separator (like whitespace) within the quoted string, or some such, to properly group the assignments (e.g. using the char class [^\s] in place of .). That's problematic if you do need to allow spaces in the quoted values, though.

Update: fixed/simplified [^\2]+?  —> .*? in the regex, because on second thought, when looking at hipowls's suggestion below, it occurred to me that (a) the backref in the character class doesn't actually work :), (b) even if it did, that part of the regex would've been redundant anyway, due to the non-greedy match...


In reply to Re: matching a line with ' and " by almut
in thread matching a line with ' and " by rhymejerky

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.