Search code examples
javascripthtmlarraysregexpreg-match

JS Regex for matching specific array increment ignoring string and seperate increment


I have the following input fields with name attributes of:

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]

I am trying to match the final [ number ] eg this part:

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

While ignoring the rest

Here is my regex pattern:

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

This affects both of the int's within brackets when I just want the last one. This regex also doesn't recognize the specific requirement of the first array key 'component'

Live regex test here:

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


Solution

  • If you want to get the last [ + digits + ], you can use

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

    See the regex demo

    Backtracking will help getting exactly the last occurrence of [digits]. Grab Group 1 value.

    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/>";
        }
    }

    UPDATE:

    To get the first [ + digits + ], you need to use lazy matching with the first dot:

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

    See another regex demo.