Javascript将字符串拆分为数组字典(键 - >值)(正则表达式)

时间:2018-05-01 23:02:21

标签: javascript regex dictionary pattern-matching

目的是在javascript中将字符串解析为数组字典。

例如,这可能是需要解析的字符串

" K = 23:3/24:32B = 43:532:45/3:3253"

我希望该字符串变成这样的字典(键 - 值)

k - 23:3/24:32

b - 43:532:45/3:3253

我最初的想法是搜索[a-Z] \ *。*并使用正则表达式将其拆分为匹配。

但是,我认为这不会起作用,因为这也会带来 b ,这不是我想要的。此外,我无法让它工作(我是正则表达式的新手)。

等于只能在键和变量之间(从不在值中)。钥匙也只是一个字,而不是一个字。

var test = "k=23:3/24:32b=43:532:45/3:3253";
var r = /(.*)([a-Z])(//*)(*.)/

以上是我的想法,但我似乎无法工作。

2 个答案:

答案 0 :(得分:2)

可能会使用/.=[^=]+(?!=)/g来匹配键值对,而无需进一步了解键和值可能包含哪些字符:

  • 此处.=匹配等号前的键(单个字符);
  • [^=]+(?!=)匹配所有非=个字符,直到下一个等号之前的一个字符(使用负向前方限制贪婪匹配)或字符串结尾;

var test = "k=23:3/24:32b=43:532:45/3:3253";

var result = {}

test.match(/.=[^=]+(?!=)/g).forEach(
  m => {
    var [k, v] = m.split('=')
    result[k] = v
  }
)

console.log(result)

答案 1 :(得分:0)

由于标识符只有一个字符,=是标识符结束且值开始的地方,因此只需使用正则表达式执行此操作:

var r = /.=.+?(?=(.=)|$)/g;

这意味着:

.          : a character
=          : followed by =
.+?        : followed by a bunch of characters (the ? means non-greedy mode: match as few as possible so that it won't consume from other variables)
(?=(.=)|$) : positive look-ahead, means that the above should be followed either by another .= (a character that is followed by =) or the end of the string

然后你可以reduce匹配来获得你想要的对象,通过split每场比赛获得键值对:

var obj = test.match(r).reduce(function(obj, match) {
    var keyValue = match.split("=");
    obj[keyValue[0]] = keyValue[1];
    return obj;
}, {});

示例:



var test = "k=23:3/24:32b=43:532:45/3:3253";
var r = /.=.+?(?=(.=)|$)/g;

var obj = test.match(r).reduce(function(obj, match) {
    var keyValue = match.split("=");
    obj[keyValue[0]] = keyValue[1];
    return obj;
}, {});

console.log(obj);