4

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.

3
  • Look here, r'^.*[\\/](.+?)\.[^.]+$' looks to be what you want. Commented Oct 1, 2019 at 9:28
  • I suggest you use the pathlib library (in the std library), it is meant to manipulate paths and is (in my opinion) very convenient. A simple Path(string).name will do Commented Oct 1, 2019 at 9:30
  • `>>> re.search(r"^.*[\\/](.+?)\.[^.]+$", "input_new/survey/argentina-attributes.csv").group(0) 'input_new/survey/argentina-attributes.csv' not working Commented Oct 1, 2019 at 9:34

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it's working.
2

Try this:

string = "input_new/survey/argentina-attributes.csv"
new_string = string.split('/')[-1].split('.')[0]
print(new_string)

1 Comment

thanks, this will work but how to do this using a regular expression.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.