【问题标题】:Regex to extract list of strings with nested brackets正则表达式提取带有嵌套括号的字符串列表
【发布时间】:2020-12-24 02:16:38
【问题描述】:

我在js中有一堆类似这样的字符串:

params[0][header][name[0]]

我需要将它们分成这样的列表:

["params", "0", "header", "name[0]"]

在找到嵌套括号之前,这很容易解决。 到目前为止,我想出的最好的就是这个正则表达式:

'params[0][header][name[0]]'.match(/([^\[]+)|\[(.+?\]?)\]/g)

返回:

["params", "[0]", "[header]", "[name[0]]"]

我可以使用,但我需要一个额外的步骤来删除不需要的括号。

我的问题是,是否有一个正则表达式可以应用于字符串并返回一个没有 extra 括号的列表?

我在 stackoverflow 和谷歌上都找不到任何解决方案。任何帮助表示赞赏。

【问题讨论】:

  • 正则表达式无法自行处理递归。
  • 我知道。我的问题是我是否可以在字符串(不是列表)上应用正则表达式并获得不带括号的列表。

标签: javascript regex


【解决方案1】:

解析括号不是正则表达式的目的。实际上用一堆括号来解析它:

function getBrackets(str) {
    const chunks = [];
    const openBrackets = [];
    let pushedFirst = false;
    for (let i = 0; i < str.length; i ++) {
        if (str[i] == "[") {
            openBrackets.push(i);
            // for pushing the first section not enclosed in brackets
            if (!pushedFirst) {
                chunks.push(str.slice(0, i));
                pushedFirst = true;
            }
        } else if (str[i] == "]") {
            const start = openBrackets.pop();
            if (openBrackets.length == 0) {
                chunks.push(str.slice(start + 1, i));
            }
        }
    }
    return chunks;
}

console.log(getBrackets("params[0][header][name[0]]")); // ["params", "0", "header", "name[0]"]

【讨论】:

    【解决方案2】:

    我的解决方案并不优雅 :-(

    const str = "params[0][header][name[0]]"
    const result = str.split(/\]\[/);
    
    const last = result[result.length - 1];
    result[result.length - 1] = last.substring(0, last.length - 1);
    
    const first = result[0]
    const idx = first.indexOf("[");
    result[0] = first.substring(0, idx);
    result.splice(1, 0, first.substring(idx + 1));
    
    console.log(result);
    

    【讨论】:

      【解决方案3】:

      这不是一个理想的解决方案,它只是分解了您的要求并使用大量检查来强制执行它们。它确实假设每个“[”都有一个匹配的“]”。它可以进一步简化,但这只是将每个需求单独分开,而不是尽可能将它们聚集在一起。

      var x = "params[0][header][name[0]]";
      var y = [];
      var z = "";
      var count = 0;
      
      for (let i = 0; i < x.length; i++) {
          if (x[i] != "[" && x[i] != "]") {
              z += x[i];
          }
          else if(x[i] == "[" && count==0){
              count += 1;
              y.push(z);
              z = "";
              
          }
          else if(x[i] == "["){
              z += x[i];
              count += 1;
          }
          else if(x[i] == "]" && count == 1){
              count -= 1;
          }
          if(x[i] == "]" && count > 1){
              count -= 1
              z+= x[i];
          }
          if(i == x.length-1){
              y.push(z);
          }
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-20
        • 2020-02-14
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 2014-10-09
        相关资源
        最近更新 更多