Reputation: 1875
How can you match the last occurrence of a regex pattern?
For example, how can I match [XXX] in:
data[X][XX][XXX]
Where X, XX, XXX could be assigned randomly.
I already tried to use a negative lookahead
\[.*?\](?!.*?\[.*?\])
But the first [ with the last ] will be matched what would not give the correct result.
Upvotes: 4
Views: 78
Reputation: 10466
You can try this for simplicity:
.*(\[.*\])
It will match upto the last occurance but will capture the last occurrence of [anything]
in group 1 and won't have to look ahead
Upvotes: 0
Reputation: 626689
The reason why you get such a result is that the .
matches a [
and ]
and any other char other than line break chars. You may replace the lazy dot with a negated character class [^][]
:
\[[^][]*\](?!.*?\[[^][]*\])
See the regex demo
Depending on the regex flavor, you may need to escape [
and ]
in the character class (in JS, ]
must be escaped ([^\][]
) and in Java/ICU you need to escape both ([^\]\[]
)).
Upvotes: 5