我使用下面的正则表达式同时搜索3种不同的字符串格式。另外,我使用re.IGNORECASE来匹配大小写字符串。但是,当我执行搜索(例如“locality”)时,我能够获得“localit”、“local”、“local”等的字符串匹配。我想和确切的词匹配(如“地点”)。在
另外,如果字符串字符之间有空格(例如,'l ocal i ty'),我想忽略它。我没有找到一个re方法来允许我这样做。我尝试使用re.ASCII,但是我得到一个错误:“…ascii无效!”如有任何帮助,我们将不胜感激。在elif searchType =='2':
print " Directory to be searched: c:\Python27 "
directory = os.path.join("c:\\","Python27")
userstring = raw_input("Enter a string name to search: ")
userStrHEX = userstring.encode('hex')
userStrASCII = ' '.join(str(ord(char)) for char in userstring)
regex = re.compile(r"(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII ))re.IGNORECASE)
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(os.path.join(root, file))
for line in f.readlines():
#if userstring in line:
if regex.search(line):
print "file: " + os.path.join(root,file)
break
else:
#print "String NOT Found!"
break
f.close()