Search code examples
regex

Regex Greedy from right to left


I have this particular code example where I would like to replace all occurrences of

[index1, index2, ..., ii] with

[ii][index1, index2, ...].

I tried the regex

(\[.*?),\s?ii\]

which I would then use in a substitution (with [ii]$1]). But the problem is that the group captures all the code from the first [ in the line to the first ii].

Take this example code line where you can clearly see the problem:

https://regex101.com/r/hhAUva/2

There it should exactly match [g, k, j, ii] and [g, ii].

How could I solve this?


Solution

  • Replace the . with a character class, that allows for everything but a [:

    (\[[^\[]*?),\s?ii\]
    

    https://regex101.com/r/hhAUva/3