-1

I have a CLASSPATH value C:\Windows\abc;C:\Windows\def;C:\Windows\ghi and need to get C:\Windows\def. Value of CLASSPATH can vary except def of middle path (or only one path \..\..\parent\def be present in CLASSPATH).

Regex is ;?(.*def) but it is matching C:\Windows\abc;C:\Windows\def

I want only C:\Windows\def regardless of presence of ; just before C:\Windows\def

What is the proper way to achieve it ?

Naive
  • 492
  • 3
  • 8
  • 20

1 Answers1

1

Greediness isn’t the issue here; rather, you need to exclude semicolons.

Match a sequence of characters not containing ; but ending in def:

[^;]*def

and make sure it’s followed by the end of the string or a ;:

[^;]*def(?=;|$)
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Now, the `[^;]*def(?=;|$)` regex will match `C:\Windows\abcdef` in `C:\Windows\abcdef;C:\Windows\def;C:\Windows\ghi`. I think OP needs to only match the value with ``\def`` at the end. – Wiktor Stribiżew Mar 31 '17 at 07:37
  • @WiktorStribiżew: OP never said that wasn’t intended, but it’s not hard to add a ``\\`` before the `def`. – Ry- Mar 31 '17 at 07:38
  • Yeah, they are usually not that talkative when asked for requirements :( – Wiktor Stribiżew Mar 31 '17 at 07:38