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) {
Solution 1:
You can use this:
functionextractParams(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"));
Solution 2:
I built a pattern that might not even need escaping \,
commas to tell them apart.
If we can assume that your keys don't contain commas, unlike the values, as in:
ke y
=
,val,ue!
is OK
k,ey
=
val,ue
is KO
Then the following pattern will work very well:
([^,]+)=(.+?)(?:(?=,[^,]+=)|$)
You can play with it here: https://regex101.com/r/RX4RsR/2
Post a Comment for "Regex Disallow A Character Unless Escaped"