【问题标题】:Json from string using regular expression使用正则表达式从字符串中提取 Json
【发布时间】:2018-03-12 01:39:54
【问题描述】:

我有一个类似的字符串:

const stringVar = ":20:9077f1722efa3632 :12:700 :77E:  :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"

我想从上面stringVar创建JSON:

{
  ":21:" : "9077f1722efa3632",
  ":12:" :  "700",
  ":27A:":  "2/2",
  ":21A:":  "9077f1722efa3632",
  ":27:" :  "1/2",
  ":40A:":  "IRREVOCABLE"
}

所以,我想我可以用正则表达式分割(":(any Of char/digit):") 我会将第一部分设为键,第二部分设为值。

【问题讨论】:

    标签: javascript json regex string


    【解决方案1】:

    正则表达式/(:\w+:)(\S+)/ 匹配整个key:value 对。您可以添加g 修饰符,然后在循环中使用它来获取所有匹配项并将它们放入对象中。

    const stringVar = ":20:9077f1722efa3632 :12:700 :77E:  :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
    
    var regexp = /(:\w+:)(\S+)/g;
    var obj = {};
    var match;
    while (match = regexp.exec(stringVar)) {
      obj[match[1]] = match[2];
    }
    console.log(obj);

    如果要创建{key: ":20:", value: "9077f1722efa3632"}的数组,可以修改代码为:

    const stringVar = ":20:9077f1722efa3632 :12:700 :77E:  :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
    
    var regexp = /(:\w+:)(\S+)/g;
    var array = [];
    var match;
    while (match = regexp.exec(stringVar)) {
      array.push({key: match[1], value: match[2]});
    }
    console.log(array);

    如果值可以包含空格,请将正则表达式更改为:

    /(:\w+:)([^:]+)\s/g
    

    这将匹配任何不包含 : 作为值的内容,但不包括最后一个空格。

    【讨论】:

    • 嘿 Barmar 感谢您的快速响应我已经使用了您的解决方案,但结果中缺少几个标签您可以试试这个字符串“:20:9077f1722efa3632:12:700:77E::27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:不可撤销 :20:NONREF :40E:EUCP 最新版本 :31D:171231 sddfsdf :51A:sdf :50:asdfasdf asdf :59:asdf asdfasdf :32B:CAD23,12 : 41A:通过 DEF 付款通知银行 :42P:100% 30 天付款 :44C:171231 :45A:dfsdf +CFR :46A:+物流 +商业发票 :47A:9077f172-18ac4c89-8131-fce442efa363 :49:CONFIRM :57A :02DFDFN" 并获取所有标签:77E: 空值
    • 我看到有些字段是相同的,如果键相同,json 会替换以前的键,所以我们可以用 [ {"name":"","value":""},{ 返回数组"名称":"","值":""}]
    • 值中有空格吗?从您的示例中,我认为空格是每个 :key:value 对之间的分隔符。
    【解决方案2】:

    不用regex也能达到同样的效果。

    const stringVar = ":20:9077f1722efa3632 :12:700 :77E:xxx :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE";
    
    const result = stringVar
      .split(' ')
      .reduce((ret, current) => {
        const pos = current.indexOf(':', 1);
        ret[current.substring(0, pos + 1)] = current.substring(pos + 1);
        return ret;
      }, {});
    
    console.log(result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 2010-10-14
      相关资源
      最近更新 更多