Regular expression to evaluate following string

85 views Asked by At

I am getting a user input in the form of

key1=value1,key2=value2,key3=value3

and there can be any number of key value pairs,

I have written following regular expression to evaluate above string.

[a-z0-9]+(:|=)[a-z0-9]+

but I am not so sure , how to check the multiple of key value pairs, this string I have written can evaluate one key value pair, I want it make it evaluate hole string of key value pairs. highly appreciate any advice on this

3

There are 3 answers

1
Phaze Phusion On BEST ANSWER

Try

([a-z0-9]+(:|=)[a-z0-9]+,?)+

To remove a trailing comma

if(str.substr(-1) === ',')
  str = str.substr(0, str.length - 1)
0
georg On

A common approach is to (ab)use replace to do the job in one shot:

str = "key1=value1,key2=value2,key3=value3"

re = /(\w+)[:=](\w+)/g

obj = {}

str.replace(re, (_, $1, $2) => obj[$1] = $2)

console.log(obj)

2
Nicolas On

Try this regex (\w+)[:=](\w+),?, in which group 1 matches the key and group 2 matches the values.

You can also use split, it might be faster.

var input = "your input";
var pairs = input.split(",")
for (i = 0; i < pairs.length; i++) {
    var parts = pairs[i].split(/[:=]/);
    var key = parts[0];
    var value = parts[1]
}