【问题标题】:Matching and returning all strings contained within [] using regex in javascript在javascript中使用正则表达式匹配并返回包含在[]中的所有字符串
【发布时间】:2014-03-26 16:02:01
【问题描述】:

我想在 javascript 中使用正则表达式匹配 [] 括号中包含的所有值。

我有以下字符串:[parent][0][child]

尝试使用正则表达式值:\[[^]]*\]

Rexex Tester 中输入这两个值会成功匹配所有内容,但是当我实际实现它时,match 只返回一个数组键值。

JS 代码:

var string = '[parent][0][child]';
regex = /\[[^]]*\]/;
match = string.match(regex);  //Returns just [0]?

我希望 match 返回一个包含所有匹配值 [parent, 0, child] 的数组

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    使用修饰符/g

    并且还要转义字符类[]中的]

    regex = /\[[^\]]*\]/g;
    

    【讨论】:

    • 谢谢,这行得通。有没有办法只返回括号内的字符串?我正在寻找带有[parent,0,child] 的数组。
    • regex = /\[([^\]]*)\]/g;
    • @JoeFrambach - 该正则表达式值仍会在结果中返回 []match.forEach(function(key){ console.log(key); }) 返回 ['[parent]','[0]','[child]'],我正在寻找 ['parent','0','child'] 作为结果集。
    • @Axel Javscript 不支持后视。否则,这可能很容易。您可以使用正面前瞻检查右侧的],并保持左侧打开,因为Jerry 在下面发布了解决方案。或者,如果您的输入与示例相同,您可以使用 .split(/[\]\[]+/) 来达到此目的。
    【解决方案2】:

    实现最终目标的替代途径:

    var str = "[parent][0][child]"
    str.split(/\[|\]/).filter(Boolean)
    

    输出["parent", "0", "child"]

    【讨论】:

    • 你可以用filter(Boolean)替换.filter(function(s){return !!s})
    • 啊,是的!太棒了
    • 不错的解决方案,而且更干净!正是我想要的结果。
    【解决方案3】:

    使用g flag 获得多个结果并修复您的正则表达式:

    regex = /\[[^\]]*\]/g;
    

    如果你想只得到括号之间的部分而不显式迭代,你可以这样做

    var matches = string.match(regex).map(function(v){ return v.slice(1,-1) })
    

    【讨论】:

      【解决方案4】:

      您可以使用前瞻来帮助仅获取方括号内的部分;假设你 100% 确定字符串有平衡的方括号:

      regex = /[^\[\]]*(?=\])/g;
      

      regex101 demo

      g 标志是匹配所有可能匹配的全局标志。

      【讨论】:

        【解决方案5】:

        你可以使用这个正则表达式:

        /[^[\[\]]+/g
        

        像这样使用它:

        var string = '[parent][0][child]';
        var regex = /[^[\[\]]+/g;
        var matches = string.match(regex);
        console.log(matches); //[parent,0,child]
        

        【讨论】:

          猜你喜欢
          • 2011-05-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多