Checking for string format using regex

Question:

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?

Asked By: Meghna Panda

||

Answers:

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")
Answered By: Tim Biegeleisen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.