Using python regular expressions how can you get a true/false returned? All python returns is
<_sre.SRE_Match object at ...>
Match objects are always true, and
None is returned if there is no match. Just test for trueness.
If you really need
False, just use
>>> bool(re.search("hi", "abcdefghijkl")) True >>> bool(re.search("hi", "abcdefgijkl")) False
As other answers have pointed out, if you are just using it as a condition for an
while, you can use it directly without wrapping in
Ignacio Vazquez-Abrams is correct. But to elaborate, re.match() will return either None, which evaluates to False, or a match object, which will always be True as he said. Only if you want information about the part(s) that matched your regular expression do you need to check out the contents of the match object.
One way to do this is just to test against the return value. Because you’re getting
<_sre.SRE_Match object at ...> it means that this will evaluate to true. When the regular expression isn’t matched you’ll the return value None, which evaluates to false.
import re if re.search("c", "abcdef"): print "hi"
hi as output.