Python regular expressions return true/false

PythonRegex

Python Problem Overview


Using Python regular expressions how can you get a True/False returned? All Python returns is:

<_sre.SRE_Match object at ...>

Python Solutions


Solution 1 - Python

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()

Solution 2 - Python

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

if re.match(...):

Solution 3 - Python

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.

Solution 4 - Python

Here is my method:

import re
# Compile
p = re.compile(r'hi')
# Match and print
print bool(p.match("abcdefghijkl"))

Solution 5 - Python

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.

Solution 6 - Python

You can use re.match() or re.search(). Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default). refer this

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnobodyView Question on Stackoverflow
Solution 1 - PythonJohn La RooyView Answer on Stackoverflow
Solution 2 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - PythoncoryView Answer on Stackoverflow
Solution 4 - PythonVaibhav DesaiView Answer on Stackoverflow
Solution 5 - PythonGavin AndereggView Answer on Stackoverflow
Solution 6 - PythonSashini HettiarachchiView Answer on Stackoverflow