首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在数组中查找对的正则表达式

在数组中查找对的正则表达式
EN

Stack Overflow用户
提问于 2018-07-24 23:15:33
回答 2查看 202关注 0票数 1

我想解析这个字符串:

[[abc.d.2,mcnv.3.we],[abec.d.2,mcnv.4.we],[abhc.d.2,mcnv.5.we]]

为了有一个键值(JSON)

{
"abc.d.2": "mcnv.3.we",
"abec.d.2: "mcnv.4.we",
"abhc.d.2": "mcnv.5.we"
}

首先,我想检查字符串是否可以解析为key=>value。如果字符串包含对,我如何检查它?

谢谢

EN

回答 2

Stack Overflow用户

发布于 2018-07-24 23:30:31

将数组解析为JSON,遍历数组,同时向目标对象添加条目,注意是否有重复的键:

let dict_target = {}; // The target dictionary, 
let src, arysrc, proceed = false;

try {
    src = "[[abc.d.2,mcnv.3.we],[abec.d.2,mcnv.4.we],[abhc.d.2,mcnv.5.we]]"
                  .replace(/,/g, '","')
                  .replace(/\]","\[/g, '"],["')
                  .replace(/^\[\[/, '[["')
                  .replace(/\]\]$/, '"]]')
             ;
    arysrc = JSON.parse(src);
    proceed = true; // Could parse the data, can carry on with processing the data
} catch (e) {
    console.log(`Source data unparseable, error '${e.message}'.`);
} 

if (proceed) {
    arysrc.forEach ( (a_item, n_idx) => {
        if (dict_target.hasOwnProperty(a_item[0])) {
           // add any tests and processing for duplicate keys/value pairs here  
           if (typeof dict_target[a_item[0]] === "string") {
               dict_target[a_item[0]] = [ dict_target[a_item[0]] ];
           }
           dict_target[a_item[0]].push(a_item[1]);
        }
        else {
           dict_target[a_item[0]] = a_item[1];
        }
    });
 } // if -- proceed
票数 1
EN

Stack Overflow用户

发布于 2018-07-25 00:15:10

下面是首先验证字符串并输出结果的代码。根本不是最优的,但任务完成得很好。

var string = '[[abc.d.2,mcnv.3.we],[abec.d.2,mcnv.4.we],[abhc.d.2,mcnv.5.we]]';
var result = (/^\[(\[.*\..*\..*\,.*\..*\..*\]\,)*\[(.*\..*\..*\,.*\..*\..*)\]\]$/g).exec(string);
if (result) {
  var r1 = result[1].replace(/\[|\]/g, '').split(',');
  var r2 = result[2].split(',');
  var output = {};

  for (var i = 0; i < r1.length -1; i +=2) {
    output[r1[i]] = r1[i+1];
  }
  output[r2[0]] = r2[1];

  console.log(output);
} else {
  console.log('invalid string');
}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51502198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档