Javascript将字符串拆分为数组字典(键->值)(正则表达式) [英] Javascript split a string into an array dictionary (key -> value) (regex)

查看:170
本文介绍了Javascript将字符串拆分为数组字典(键->值)(正则表达式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The aim is to parse a string into an array dictionary in javascript.

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

For example this maybe the string that needs to be parsed

k = 23:3/24:32b = 43:532:45/3:3253

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

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

k-23:3 / 24:32

k - 23:3/24:32

b-43:532:45/3:3253

b - 43:532:45/3:3253

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

My initial idea was to search for [a-Z]\*.* and split it into matches using regex.

但是,我不认为这会起作用,因为这也会带来 b ,这不是我想要的。另外,我无法使它正常工作(我是regex的新手)。

However, I do not think this would work as this would also bring over b which is not what I want. Also, I was not able to get this to work (I'm new to regex).

仅等于永远在键和变量之间(永远不在值中)。密钥也只能是单个字符而不是单词。

An equals will only ever be between a key and variable (never in the value). The key will also only ever be a single character not a word.

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

上面是我打算做的事情,但我似乎什么也没用。

Above was my idea of going about it but I can not seem to get anything to work.

推荐答案

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

Possibly use /.=[^=]+(?!=)/g to match the key value pair without further knowledge of what characters are possible for the key and value:


  • 此处。= 与等号前的键(单个字符)匹配;

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

  • Here .= matches the key (single character) right before the equal sign;
  • [^=]+(?!=) matches all non = characters after until one character before the next equal sign (restrict the greedy match using a negative look ahead) or the end of string;

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)

这篇关于Javascript将字符串拆分为数组字典(键->值)(正则表达式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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