Question

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'
Was it helpful?

Solution

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.

OTHER TIPS

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

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top