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

Checking for string format using regex

This is an easy question, but I am still getting stuck. I have a bunch of files and I have to check whether they are following this format.

abc_monthname[0-9]_v[0-9].xlsx

I have done some very generic like : r^[A-Za-z]+_[A-Za-z0-9]+_v[0-9]+\.xlsx$''
but this will fail for some cases. I want to give a strict rule. How do I achieve this in python?

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 :

You probably want to use + quantifiers with the numeric portion of your regex:

^abc_monthname[0-9]+_v[0-9]+\.xlsx$

Note also that dot is a metacharacter and should be escaped with backslash. Here is a sample script

filename = "^abc_monthname123_v2.xslx"
if re.search(r'^abc_monthname[0-9]+_v[0-9]+\.xlsx$', filename):
    print("MATCH")
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