RegEx disallow a character unless escaped

五迷三道 提交于 2019-12-12 12:26:24

问题


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.


回答1:


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"));



回答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



来源:https://stackoverflow.com/questions/40466141/regex-disallow-a-character-unless-escaped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!