从Javascript上的字符串中提取带有正则表达式的Key:Value对assoc

时间:2018-12-11 19:59:38

标签: javascript regex

我有以下字符串

server:all, nit:4545, search:dql has map

使用正则表达式/(\w+):((?:"[^"]*"|[^:,])*)/g我得到

["server:all", "nit:4545", "search:dql has map"] //Array

但是我想得到

{server:"all","nit":"4545","search":"dql has map"}

OR

[{server:"all"},{"nit":"4545"},{"search":"dql has map"}]

3 个答案:

答案 0 :(得分:1)

您可以为key:value使用一个简单的正则表达式,并使用exec使用外观:

var str = 'server:all, nit:4545, search:dql has map';
var re = /([\w-]+):([^,]+)/g;

var m;
var map = {};

while ((m = re.exec(str)) != null) {
  map[m[1]] = m[2];
}

console.log(map);

答案 1 :(得分:0)

您可以使用String#replace循环匹配和捕获,并将其分配给空对象。

const string = 'server:all, nit:4545, search:dql has map';
const regex = /(\w+):((?:"[^"]*"|[^:,])*)/g;
const map = {};

string.replace(regex, (m, c1, c2) => {
  map[c1] = c2;
});

console.log(map);

答案 2 :(得分:0)

对于示例数据,您还可以先用逗号split,然后用冒号分隔:

let str = "server:all, nit:4545, search:dql has map";
let result = {};
str.split(',').forEach(function(elm) {
  [k, v] = elm.trim().split(':');
  result[k] = v;
});

console.log(result);