Search code examples
regexregex-lookaroundspcreregex-greedy

Regex to extract multidimensional keys using bracket notation


I need to retrieve all keys using pure regex. I need to start with word field and after that need to capture all multiple keys..

field[somevalue][anothervalue]

I'm using this regex: /^field(?=\[(\w+)](?=\[(\w+)])?)/

But I can retrieve only two levels (somevalue and anothervalue)

I need to go deep and retrieve another levels like:

field[somevalue][anothervalue][other][some]...

So I need to retrieve somevalue, anothervalue, other, some and so on, starting with variable name field

I don't want to use loops like this (Regex for bracket notation of multi-dimensional array)

Need to pass directly and use in https://regex101.com


Solution

  • Start the match with either a look behind for field or the end of the previous match (\G):

    (?<=field|\G)\[(.*?)]
    

    See live demo.