简体   繁体   中英

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.

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 ( [^\\]\\[] )).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM