本文介绍了除非转义,否则 RegEx 不允许字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我解析逗号分隔键值对的正则表达式:
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;
}
例如结果:
extractParams("arg1 = value1 ,arg2 = value2 ,arg3=uuu")
是{"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")
将会
{"arg1":"val,ue1","arg2":"value=e2","arg3":"val\ue3"}
.
我该怎么做?谢谢,摩西.
How can I do that? Thanks, Moshe.
推荐答案
你可以使用这个:
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"));
这篇关于除非转义,否则 RegEx 不允许字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!