RegEx禁止字符,除非已转义 [英] RegEx disallow a character unless escaped

查看:94
本文介绍了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":"valu=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禁止字符,除非已转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆