怎么做 '?'不油腻

How to make '?' non gready

我有一个 CLASSPATH 值 C:\Windows\abc;C:\Windows\def;C:\Windows\ghi 并且需要获取 C:\Windows\def。 CLASSPATH 的值可以变化,但中间路径 def 除外(或者 CLASSPATH 中只有一个路径 \..\..\parent\def 存在)。

正则表达式是 ;?(.*def) 但它匹配 C:\Windows\abc;C:\Windows\def

我只想要 C:\Windows\def,而不管 ;C:\Windows\def

之前是否存在

实现它的正确方法是什么?

贪婪不是这里的问题;相反,您需要排除分号。

匹配不包含 ; 但以 def:

结尾的字符序列
<b>[^;]*def</b>

并确保其后跟字符串末尾或 ;:

[^;]*def<b>(?=;|$)</b>