views:

632

answers:

2

I'm having trouble writing a regular expression (suitable for PHP's preg_match()) that will parse keyword='value' pairs regardless of whether the <value> string is enclosed in single or double quotes. IOW in both of the following cases I need to get the <name> and <value> where the <value> string may contain the non-enclosing type of quotes:

name="value"
name='value'
+11  A: 

In Perl this is a regular expression that would work. It first matched for the start of the line then matches for one or more non = characters and sets them to $1. Next it looks for the = then the a non parentheses with a choice of matching for " or ' and sets that to $2.

/^([^=]+)=(?:"([^"]+)"|'([^']+)')$/

If you wanted it to match blank expressions like.

This=""

Replace the last two + with an * Otherwise this should work

Edit As mentioned in the comments. Doug used...

 /^\s?([^=]+)\s?=\s?("([^"]+)"|\'([^\']+)\')\s?/

This will match one optional white space on ether end of the input or value and he has removed the end of line marker.

Copas
it will match name='asd" with a double quote at the and, that's not correct.
Andrea Ambu
No longer matches non matching quote sets.
Copas
argh! you updated it before my response :P
Andrea Ambu
deleted mine since this one was here first and working :D
Andrea Ambu
This isn't quite right. /^([^=]+)=(?:"([^"]+)"|'([^']+)')"$/I believe the double quote before the end-of-line metacharacter shouldn't be there.
Doug Kaye
@Doug - It is a honor to be corrected by the publishers of IT Conversations :). Thanks corrected.
Copas
Here's the final version I used. It's escaped for single quotes and is more forgiving for whitespace. Thanks for the help!/^\s?([^=]+)\s?=\s?("([^"]+)"|\'([^\']+)\')\s?/
Doug Kaye
+2  A: 
/^(\w+?)=(['"])(\w+?)\2$/

Which will place the key in $1 and the value in $3.

Cirno de Bergerac