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.
Regular expressions (regex) are essentially text patterns that you can use to automate searching through and replacing elements within strings of text.
Python re. match() method looks for the regex pattern only at the beginning of the target string and returns match object if match found; otherwise, it will return None.
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()
Match
objects are always true, and None
is returned if there is no match. Just test for trueness.
if re.match(...):
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"
Produces hi
as output.
Here is my method:
import re
# Compile
p = re.compile(r'hi')
# Match and print
print bool(p.match("abcdefghijkl"))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With