简体   繁体   English

如何使用正则表达式匹配模式的最后一次出现

[英]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. 我想使用正则表达式匹配{{token2}}

other possible cases that it should match are 它应该匹配的其他可能情况

{{token1}}/{ should match { (the last one). {{token1}}/{应匹配{ (最后一个)。

{{token1}}/{{ should match {{ (the last one). {{token1}}/{{应该匹配{{ (最后一个)。

{{token1}}/{{token2 should match {{token2 . {{token1}}/{{token2应匹配{{token2

I tried /\\S+$/ but it works when the string is {{token1}} {{token2}} . 我尝试了/\\S+$/但是当字符串为{{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 RegEx演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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