Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need regex to parse keyword='value' with single or double quotes

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'
like image 752
Doug Kaye Avatar asked Jun 07 '09 15:06

Doug Kaye


3 Answers

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.

like image 118
Copas Avatar answered Sep 22 '22 23:09

Copas


/^(\w+?)=(['"])(\w+?)\2$/

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

like image 35
Nietzche-jou Avatar answered Sep 19 '22 23:09

Nietzche-jou


A few years late, but since this question is highly ranked on google, and the answers didn't satisfy my needs, here's another expression:

(?<key>\w+)\s*=\s*(['"]?)(?<val>(?:(?!\2)[^\\]|\\.|\w)+)\2

This will match single or double quotes, taking into account escaped quotes, and unquoted values.

name = bar
name = "bar"
name = 'bar'
name = "\"ba\"r\""

It, however, does have a limitation in that if a value is missing the key from the next key/value pair is read. This can be addressed by using a comma separated list of key/value pairs.

like image 34
Twifty Avatar answered Sep 19 '22 23:09

Twifty