Python regular expression file name match

Viewed 523

Hi i needed my regular expression code to find matching filenames in a specific format such as ankit_bill_2019-12-02-00_abc01.csv or ankit_bill_2019-12-02-00_abc.csv etc. The last characters of file should have only these specific values e.g abc,abc01,abc02,cde,cde01. Other then this an email should be sent with unmatched file names.Here the email function is called for both match and unmatch i only want it to be called for unmatch values.

##Packages used
import os
import re
import sys
import glob
import pandas as pd

def sendMail(msg):
    a=''
    for i in msg:
        a+="%s\n" %i

   # a = "File Name Not Valid:\n ".join(str(i) for i in msg)

    sendmail_location = "/usr/sbin/sendmail" # sendmail location
    p = os.popen("%s -t" % sendmail_location, "w")
    p.write("From: %s\n" % "abc@zy.com")
    p.write("To: %s\n" % "abc@zy.com")
    p.write("Subject:File Name Not Valid\n")
    p.write("\n") # blank line separating headers from body
    p.write("File Name Is Not Valid:\n"+a)
    status = p.close()
    if status != 0:
        print "Sendmail exit status", status
        #return msg


##file match
match=[]
not_match=[]
try:
    for file in glob.glob('*.csv'):
        r = re.search(r'ankit_bill_(20[0-9][0-9])-([1-9]|1[0-2]|0[0-9])-([1-9]|1[0-9]|2[0-9]|3[0-1]|0[0-9])-[0-9]{2}_[a-z0-6]]{3,5}.csv', file)
        if r:
            match.append(file)
        if not r:
            not_match.append(file)
    sendMail(not_match)
except Exception:
    not_found="File Not Found"
    sendMail(not_found)
#print(match)
#print(not_match)
2 Answers

You could make the regex as bit more specific changing the end of the pattern from [a-z0-6]]{3,5}.csv to (?:abc|cde)[0-6]{0,2}\.csv\b

Note that there is a ] too much in the pattern and the . has to be escaped to match it literally.

\bankit_bill_20[0-9][0-9]-(?:[1-9]|1[0-2]|0[0-9])-(?:[1-9]|1[0-9]|2[0-9]|3[0-1]|0[0-9])-[0-9]{2}_(?:abc|cde)[0-6]{0,2}\.csv\b

If instead of abc and def there should be 3 lowercase characters, use [a-z]{3}[0-6]{0,2}\.csv\b

Regex demo

Add this as if the filenames are matching as not _match will become empty list and if that's the case add this condition to terminate the function if len(a): sys.exit(0)

Related