import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
print 'matched'
The best one by far is
bool(re.search('ba[rzd]', 'foobarrrr'))
Returns True
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
.
Here's a function that does what you want:
import re
def is_match(regex, text):
pattern = re.compile(regex)
return pattern.search(text) is not None
The regular expression search method returns an object on success and None if the pattern is not found in the string. With that in mind, we return True as long as the search gives us something back.
Examples:
>>> is_match('ba[rzd]', 'foobar')
True
>>> is_match('ba[zrd]', 'foobaz')
True
>>> is_match('ba[zrd]', 'foobad')
True
>>> is_match('ba[zrd]', 'foobam')
False
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