Reputation: 39
I'm in need of an expression for finding a name in a dynamic path string.
Basically I need to find a string before last >
character and it must be inside these >
characters.
Lets say I have this string:
"Category 1 > Category 1.1 > Category 1.1.1"
With this expression \>(.*)\>
it works, and I get the desired string which is "Category 1.1"
.
The problem is if this string doesn't have a >
at the beggining.
E.g.
"Category 1.1 > Category 1.1.1"
I tried something like this \>?(?=>)?\>?(.*)\>
and this works but only for this case. When I test it with "Category 1 > Category 1.1 > Category 1.1.1"
, it returns Category 1 > Category 1.1 >
which is wrong.
Upvotes: 2
Views: 396
Reputation: 626689
You may use
[^>]+(?=>[^>]*$)
See the regex demo. For both the test cases you have, it matches Category 1.1
text.
Details
[^>]+
- 1+ chars other than >
(?=>[^>]*$)
- a positive lookahead that requires >
and then 0+ chars other than >
up to the end of the string.Note you may want to trim()
/ strip()
the result afterwards with the appropriate method your environment provides.
Upvotes: 1