Match
objects are always true, and None
is returned if there is no match. Just test for trueness.
Code:
>>> st = 'bar'
>>> m = re.match(r"ba[r|z|d]",st)
>>> if m:
... m.group(0)
...
'bar'
Output = bar
If you want search
functionality
>>> st = "bar"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m is not None:
... m.group(0)
...
'bar'
and if regexp
not found than
>>> st = "hello"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m:
... m.group(0)
... else:
... print "no match"
...
no match
As @bukzor mentioned if st = foo bar
than match will not work. So, its more appropriate to use re.search
.