jac0117
jac0117

Reputation: 77

Regular expression to match name value pairs

I'm trying to come up with a regular expression that will match name=value pairs.

pet=dog  (valid)
pet=dog&fruit=apple (valid)

pet=dog& (invalid - & must be followed by name value pair)
pe t=dog (invalid - space in name)
pet=d og (invalid - space in value)
pet=dog&&fruit=apple (invalid - two & signs)
pet=dog=cat&fruit=apple (invalid - two = signs before new name value pair)
pet==dog (invalid two = signs)

Upvotes: 1

Views: 1378

Answers (2)

Adrian
Adrian

Reputation: 46462

Presuming you don't need to support escaping and there are no invalid characters in a name or value other than & and =, you could use something along these lines:

^([^&= ]+)=([^&= ]+)(&([^&= ]+)=([^&= ]+))*$

That is: start of string, capture one or more characters that aren't & or =, then an =, then capture one or more characters that aren't & or =; then capture zero or more repetitions of that entire first expression prefixed with an ampersand, then the end of the string.

Or, put another way, there must be at least one name-value pair, and if there's more than one, subsequent name-value pairs must start with an ampersand, and there can be any number of them. Nothing can come before or after the matched expressions (this prevents strings starting or ending with & or =).

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 31025

You can use a regex like this:

^\w+=\w+(?:&\w+=\w+)*$

Working demo

Regular expression visualization

enter image description here

Upvotes: 1

Related Questions