The Python Oracle

Python regular expressions return true/false

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping

--

Chapters
00:00 Question
00:23 Accepted answer (Score 177)
00:39 Answer 2 (Score 237)
01:05 Answer 3 (Score 15)
01:18 Answer 4 (Score 11)
01:44 Thank you

--

Full question
https://stackoverflow.com/questions/6576...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #regex

#avk47



ANSWER 1

Score 257


If you really need True or False, just use bool

>>> 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 if or while, you can use it directly without wrapping in bool()




ACCEPTED ANSWER

Score 182


Match objects are always true, and None is returned if there is no match. Just test for trueness.

if re.match(...):



ANSWER 3

Score 12


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.




ANSWER 4

Score 9


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"

Produces hi as output.