Gissipi_453 Gissipi_453 - 1 month ago 12
Javascript Question

Regex for key value pair

I have a regex

(\w+)\s*:((?:\w+[-+*%])*?\w+)$


that matches key value pair like these -


key:value

key2:value2


But the regex match fails if the key and value are within paranthesis like these -


"key":value

"key2":"value2"


What modification can be done to make the regex match key and value within paranthesis also ?

Answer

You can use optional quotes on either side of key-value pairs like this:

/("?)\b(\w+)\1\s*:\s*("?)((?:\w+[-+*%])*?\w+)\b\3/g

RegEx Demo

Take note of group ("?) that captured an empty string or a double quote. On the other side we use a back-reference \1 of this group for closing quote.