JS Regex用于匹配特定的数组增量,忽略字符串和单独的增量

时间:2016-05-27 07:16:37

标签: javascript html arrays regex preg-match

我有以下输入字段,其名称属性为:

carousels['components'][0][0][title]
carousels['components'][0][1][title]
carousels['components'][0][2][title]

carousels['components'][1][0][title]
carousels['components'][1][1][title]
carousels['components'][1][2][title]

carousels['components'][2][0][title]
carousels['components'][2][1][title]
carousels['components'][2][2][title]

我试图匹配最后的[数字],例如这部分:

carousels['components'][2][THIS][title]
carousels['components'][2][THIS][title]
carousels['components'][2][THIS][title]

忽略其余的

这是我的正则表达式模式:

/(\[[^components\]])+(\[*])/

当我只想要最后一个时,这会影响括号内的两个int。这个正则表达式也没有认识到第一个数组键组件的特定要求'

现场正则表达式测试:

http://www.regexpal.com/?fam=94974

2 个答案:

答案 0 :(得分:1)

你可以试试这个

    ^.*(\[.*?\])\[.*?\]$
       <------->
Match in this(1st captured group)

<强> Regex Demo

如果您想完全匹配['components'],则可以使用

^.*\['components'\].*(\[.*?\])\[.*?\]$

答案 1 :(得分:1)

如果您想要最后 [ + digits + ] ,可以使用

/^.*\[(\d+)\].*$/

请参阅regex demo

回溯将有助于准确获取[digits]的最后一次出现。抓住第1组值。

var re = /^.*\[(\d+)\].*$/; 
var str = 'carousels[\'components\'][0][0][title]\ncarousels[\'components\'][0][1][title]\ncarousels[\'components\'][0][2][title]\n\ncarousels[\'components\'][1][0][title]\ncarousels[\'components\'][1][1][title]\ncarousels[\'components\'][1][2][title]\n\ncarousels[\'components\'][2][0][title]\ncarousels[\'components\'][2][1][title]\ncarousels[\'components\'][2][2][title]';

for (var s of str.split("\n")) {
    var res = (m=re.exec(s)) ? m[1] : "";
    if (res) {
      document.body.innerHTML += s + ": " + res + "<br/>";
    }
}

<强>更新

要获取第一个 [ + digits + ] ,您需要使用与第一个点的延迟匹配:

/^.*?\[(\d+)\].*$/
    ^ - Here, the ? will make matching lazy/reluctant 
        (it will match any 0+ chars other than a newline as few as possible)

请参阅another regex demo

相关问题