问题描述
嗨,我需要我的正则表达式代码来查找特定格式的匹配文件名,例如ankit_bill_2019-12-02-00_abc01.csv或ankit_bill_2019-12-02-00_abc.csv等。文件的最后一个字符应仅包含这些字符特定值,例如abc,abc01,abc02,cde,cde01。否则,这封电子邮件应发送不匹配的文件名。在这里,电子邮件函数既要匹配也要不匹配,而我只希望调用不匹配值。
##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" % "[email protected]")
p.write("To: %s\n" % "[email protected]")
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
添加此文件,就好像文件名匹配而不是_match一样将成为空列表,如果是这样,请添加此条件以终止函数if len(a): sys.exit(0)