Search code examples
regexnon-greedy

How to make '?' non gready


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 ?


Solution

  • 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(?=;|$)