在python中去除正则表达式

tel*_*tel 1 python regex greedy non-greedy

我正在尝试编写一个正则表达式,它将完整路径文件名转换为给定文件类型的短文件名,减去文件扩展名.

例如,我试图从字符串中获取.bar文件的名称

re.search('/(.*?)\.bar$', '/def_params/param_1M56/param/foo.bar')
Run Code Online (Sandbox Code Playgroud)

根据Python re docs,*?是不合适的版本*,所以我期待得到

'foo'
Run Code Online (Sandbox Code Playgroud)

返回,match.group(1)但我得到了

'def_params/param_1M56/param/foo'
Run Code Online (Sandbox Code Playgroud)

我在这里想到的贪婪是什么?

gee*_*aur 8

你所缺少的不仅仅是关于正则表达式引擎的贪婪:它们从左到右工作,所以/尽可能早地匹配,.*?然后强制从那里开始工作.在这种情况下,最好的正则表达式根本不涉及贪婪(你需要回溯才能工作;它会,但如果有很多斜杠,可能需要很长时间才能运行),但更明确的模式:

'/([^/]*)\.bar$'
Run Code Online (Sandbox Code Playgroud)