2

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.

bMikolaj
  • 39
  • 1
  • 7
  • Wait, do you expect `Category 1.1` in `Category 1.1 > Category 1.1.1`? Then, you may try `[^>]+(?=>[^>]*$)`. – Wiktor Stribiżew Jun 21 '19 at 07:55
  • It must return a category between > > characters or the string before last >. The problem is that this is dynamic. So with the last expression that you wrote the string Category 1 > Category 1.1 > Category 1.1.1 returns Category 1.1.1 which is wrong and it should return Category 1.1 – bMikolaj Jun 21 '19 at 08:02
  • Check https://regex101.com/r/WgjRra/1, in `Category 1 > Category 1.1 > Category 1.1.1`, I get a `Category 1.1` match. – Wiktor Stribiżew Jun 21 '19 at 08:03

1 Answers1

1

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • @bruno_mikolaj Note I used `\n` in the demo only because the test is performed against a multiline string while in real life you will be using the regex against standalone strings. – Wiktor Stribiżew Jun 21 '19 at 08:07