简体   繁体   中英

How to match the last occurrence of a pattern using regex

I have a string like

{{token1}}/{{token2}}

I want to match {{token2}} using regex.

other possible cases that it should match are

{{token1}}/{ should match { (the last one).

{{token1}}/{{ should match {{ (the last one).

{{token1}}/{{token2 should match {{token2 .

I tried /\\S+$/ but it works when the string is {{token1}} {{token2}} .

Thanks in advance.

You can use a negative lookahead regex:

/{+[^}]*}*(?!.*{)/

(?!.*{) is negative lookahead that asserts we don't have any { ahead of the current position.

RegEx Demo

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