'''匹配字符创建 文件并写入'''import codecsimport osimport re# (upstream)\s+(\S+)\s+([^}]+)}file = "ga10.wms5.jd.com.txt"name = "upstream"'''匹配upstreamreg = re.compile(r"(upstream)\s+(\S+)\s+([^}]+)}")text= reg.findall()print(text)(upstream)\s+(\S+)\s+([^}]+)} ^(upstream)\s+(\S+)\s+{[^}]+} -- no\s*(upstream\s+(\S+)\s+{[^}]+})'''
# ([^}]+) 不以}开头with codecs.open(file) as f: # reg = re.compile(r"") reg = re.compile(r"\s*(upstream\s+(\S+)\s+{[^}]+})") text= reg.findall(f.read()) if not os.path.exists(name): # 目录不存在时创建 os.mkdir(name) os.chdir(name) for i in text: with codecs.open(i[1],"w") as fw: fw.write(i[0]) os.chdir("..")
'''匹配location(location\s+/(\S+)/\s+{\s+proxy_next_upstream.*?[^}]*?})'''loca = "location"reLo = re.compile(r"(location\s+/(\S+)/\s+{\s+proxy_next_upstream.*?[^}]*?})")with codecs.open(file) as fl: textLo = reLo.findall(fl.read()) if not os.path.exists(loca): os.mkdir(loca) os.chdir(loca) for each in textLo: ff = each[1] + ".location.conf" with codecs.open(ff,"w") as flw: flw.write(each[0]) os.chdir("..")