Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx disallow a character unless escaped

below is my regex to parse comma separated key-value pairs:

function extractParams(str) {
    var result = {};
    str.replace(/\s*([^=,]+)\s*=\s*([^,]*)\s*/g, function(_, a, b) { result[a.trim()] = b.trim(); });
    return result;
}

For example the result of:

extractParams("arg1 = value1 ,arg2    = value2 ,arg3=uuu")

is {"arg1":"value1","arg2":"value2","arg3":"uuu"}.

I want to extend this function to allow the values include escaped commas, equals signs and the escape character itself. Such that the result of:

extractParams("arg1 = val\,ue1 ,arg2 = valu\=e2, arg3= val\\ue3")

will be

{"arg1":"val,ue1","arg2":"valu=e2","arg3":"val\ue3"}.

How can I do that? Thanks, Moshe.

like image 813
Moshe Avatar asked Nov 16 '25 16:11

Moshe


1 Answers

You can use this:

function extractParams(str) {
    var result = {};
    str.replace(/\s*((?:\\[,\\=]|[^,\\=]*)+)\s*=\s*((?:\\[,\\=]|[^,\\=]*)+)\s*/g, function(_, a, b) { result[a.trim()] = b.trim(); });
    return result;
}

console.log(extractParams("arg1 = val\\,ue1 ,arg2 = valu\\=e2, arg3= val\\\\ue3"));
like image 141
Thomas Ayoub Avatar answered Nov 19 '25 05:11

Thomas Ayoub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!