Regex case-insensitive searches not matching the exact word
I'm using the following regex to search for 3 different string formats, concurrently. Additionally, I'm using re.IGNORECASE
to match upper and lower case strings. However, when I perform a search (e.g. 'locality'), I'm able to get string matches for 'localit', 'locali', 'local' and so on and so forth. I want to match the exact word (eg. 'locality').
Also, if there is white space between string characters (eg., 'l ocal i ty'
), I want to ignore it. I have not found a re
method that allows me to do that. I tried using re.ASCII
, but I get an error: "...ascii is invalid!" Any assistance is appreciated.
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开发者_如何学JAVA( 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()
There is no such flag in re, so either:
construct a regex with explicit whitespace-matching after every char:
r'\s*'.join(c for c in userStrASCII)
This works:
myre.findall(line)
finds 'l Oc ALi ty'or (if you only need to detect matches to the pattern, but not do anything further with the actual match text) use
string.translate(,deleteChars)
to strip whitespace from the line before matching. e.g. doline.translate(None, ' \t\n\r').lower()
before you try to match. (Keep a copy of the unsquelched line.)
精彩评论