Python正则表达式文件名匹配

Python regular expression file name match

您好,我需要我的正则表达式代码来查找特定格式的匹配文件名,例如 ankit_bill_2019-12-02-00_abc01.csv 或 ankit_bill_2019-12-02-00_abc.csv 等。文件的最后一个字符应该只有这些特定值,例如 abc、abc01、abc02、cde、cde01。除此之外,这封电子邮件应该与不匹配的文件一起发送 names.Here 匹配和不匹配都会调用电子邮件功能,我只想为不匹配的值调用它。

##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)

您可以使正则表达式更具体一些,将模式的结尾从 [a-z0-6]]{3,5}.csv 更改为 (?:abc|cde)[0-6]{0,2}\.csv\b

请注意,模式中的 ] 太多,必须转义 . 才能按字面意思匹配它。

\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

如果应该使用 3 个小写字符而不是 abc 和 def,请使用 [a-z]{3}[0-6]{0,2}\.csv\b

Regex demo

添加这个就好像文件名匹配一样,因为不匹配将变成空列表,如果是这种情况,添加这个条件来终止函数 if len(a): sys.exit(0)