Laurence
Laurence

Reputation: 1875

Regex, match the last pattern

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

Answers (2)

Mustofa Rizwan
Mustofa Rizwan

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

Explanation

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions