I’m not sure why this isn’t working:
import re
import csv
def check(q, s):
match = re.search(r'%s' % q, s, re.IGNORECASE)
if match:
return True
else:
return False
tstr = []
# test strings
tstr.append('testthisisnotworking')
tstr.append('This is a TEsT')
tstr.append('This is a TEST mon!')
f = open('testwords.txt', 'rU')
reader = csv.reader(f)
for type, term, exp in reader:
for i in range(2):
if check(exp, tstr[i]):
print exp + " hit on " + tstr[i]
else:
print exp + " did NOT hit on " + tstr[i]
f.close()
testwords.txt contains this line:
blah, blah, test
So essentially ‘test’ is the RegEx pattern. Nothing complex, just a simple word. Here’s the output:
test did NOT hit on testthisisnotworking
test hit on This is a TEsT
test hit on This is a TEST mon!
Why does it NOT hit on the first string? I also tried \s*test\s* with no luck. Help?
Adding a
print repr(exp)to the top of the firstforloop shows thatexpis' test', note the leading space.This isn’t that surprising since
csv.reader()splits on commas, try changing your code to the following:Note that in addition to the
strip()call which will remove the leading a trailing whitespace, I change your second for loop to just loop directly over the strings intstrinstead of over a range. There was actually a bug in your current code becausetstrcontained three values but you only checked the first two becausefor i in range(2)will only give youi=0andi=1.