in reply to matching a line with ' and "

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...

Replies are listed 'Best First'.
Re^2: matching a line with ' and "
by Skeeve (Parson) on Jul 18, 2008 at 09:17 UTC

    No, almut. It might look ugly, but it's the correct output. It might be a typo, but that's what we programmers have to deal with ;-)


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

      Yes, it's correct from a purely syntactic point of view. Still, it's presumably not what the OP had in mind...

      Anyhow, I just wanted to point out that there's a general disambiguation problem, in case the OP needs to allow arbitrary quoted content, which might contain the very separator that's used to split up the individual key-value expressions. It's unclear from the given spec, however, whether that's the case.