如何使用正则表达式从字符串中提取文件名

om *_*thi 4 python regex python-3.x

我是正则表达式的新手,并尝试从基本上是文件路径的字符串中提取文件名。


string = "input_new/survey/argentina-attributes.csv"
string_required = argentina-attributes

Run Code Online (Sandbox Code Playgroud)

我知道我可以通过下面的代码来做到这一点。

string.split('/')[2].split('.')[0]
Run Code Online (Sandbox Code Playgroud)

但我希望通过使用正则表达式来做到这一点,因此如果将来路径的格式发生变化(input_new/survey/path/path/argentina-attributes.csv)不应影响输出。

我知道以前问过类似的问题,但我正在寻找一种适合我的用例的模式。

sha*_*eed 5

尝试这个,

>>> import re
>>> string = "input_new/survey/argentina-attributes.csv"
Run Code Online (Sandbox Code Playgroud)

输出:

>>> re.findall(r'[^\/]+(?=\.)',string) # or re.findall(r'([^\/]+)\.',string)
['argentina-attributes']
Run Code Online (Sandbox Code Playgroud)

从这里引用


归档时间:

查看次数:

10199 次

最近记录:

6 年,4 月 前