Home > Software design >  Checking for string format using regex
Checking for string format using regex

Time:10-17

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?

CodePudding user response:

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")
  • Related