Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Allowing files with proper names using Regex

Here are different files and the output which should look like:

  1. abc.csv – Correct
  2. abc.csv.gz – Fail
  3. abc.csv.csv – Fail
  4. abc.def.csv – Correct

The present regex looks like .*[.]csv$ which passes cases 1 and 2, but not 3 and 4. I tried using {} and \B to allow only 1 extension but wasn’t able to make it correctly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As said in the comments, filename.endswith('.csv') is in my opinion the most pythonic option.

That said, if you want to use a regex, you can use re.match('.*(?<!\.csv)(\.csv)$', s) or re.fullmatch('.*(?<!\.csv)(\.csv)', s)

s = 'abc.csv.csv'
re.match('.*(?<!\.csv)(\.csv)$', s)
# no match

s = 'abc.def.csv'
re.match('.*(?<!\.csv)(\.csv)$', s)
#<re.Match object; span=(0, 11), match='abc.def.csv'>

regex demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading