Search code examples
.netregexregex-lookarounds

Regex Match all characters after last occurrence (and before first occurrence)


I'm having trouble figuring out a regex pattern that will match all characters after last occurrence of '<' and before first occurrence '>'.

Here's an example string: test1 <test2 <test3> <<test4> test5>>

the result should be test4

I've tried searching but haven't had any luck finding an example close enough to make sense to me.


Solution

  • Try this expression: ^.*?<(?=[^<]*$)([^>]+)>.*$

    The first captured group is the text you are looking for, demo: https://regex101.com/r/sUY6x8/2

    Logic being, find the last opening bracket (using a lookahead), and then match till a closing bracket