Regex, matches the latest pattern

How can you match the last occurrence of a regex pattern?

For example, how can I match [XXX] to:

data[X][XX][XXX]

Where X, XX, XXX can be assigned randomly.

I already tried to use negative view

\[.*?\](?!.*?\[.*?\])

But the first [with the last] will correspond to that which does not give the correct result.

+4
source share
2 answers

The reason why you get such a result is that the .matches [and ]and any other char, other than a line break character. You can replace the lazy point with a negative character class [^][]:

\[[^][]*\](?!.*?\[[^][]*\])

Watch the regex demo

[ ] ( JS, ] ([^\][]), Java/ICU ([^\]\[])).

+5

:

.*(\[.*\])

, [anything] 1

0

Source: https://habr.com/ru/post/1665689/


All Articles