Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the filename from a string using regular expression [duplicate]

I am new in the regular expression and trying to extract the file name from a string which is basically a file path.


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

i know i can do this by below code.

string.split('/')[2].split('.')[0]

but I am looking to do this by using regular expression so if in future the formate of the path changes(input_new/survey/path/path/argentina-attributes.csv) should not affect the output.

i know kind of similar question asked before but I am looking for a pattern which will work for my use case.

like image 801
om tripathi Avatar asked Nov 02 '25 14:11

om tripathi


2 Answers

Try this,

>>> import re
>>> string = "input_new/survey/argentina-attributes.csv"

Output:

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

Referred from here

like image 53
shaik moeed Avatar answered Nov 04 '25 04:11

shaik moeed


Try this:

string = "input_new/survey/argentina-attributes.csv"
new_string = string.split('/')[-1].split('.')[0]
print(new_string)
like image 26
Kostas Charitidis Avatar answered Nov 04 '25 04:11

Kostas Charitidis