python's re: return True if string contains regex pattern


I have a regular expression like this:

regexp = u'ba[r|z|d]'

Function must return True if word contains bar, baz or bad.
In short, I need regexp analog for Python’s

'any-string' in 'text'

How can I realize it? Thanks!

Asked By: ghostmansd



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


>>> st = 'bar'
>>> m = re.match(r"ba[r|z|d]",st)
>>> if m:

Output = bar

If you want search functionality

>>> st = "bar"
>>> m ="ba[r|z|d]",st)
>>> if m is not None:

and if regexp not found than

>>> st = "hello"
>>> m ="ba[r|z|d]",st)
>>> if m:
... else:
...   print "no match"
no match

As @bukzor mentioned if st = foo bar than match will not work. So, its more appropriate to use

Answered By: RanRag
import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
Answered By: mattbornski

You can do something like this:

Using search will return a SRE_match object, if it matches your search string.

>>> import re
>>> m ='ba[r|z|d]', 'bar')
>>> m
<_sre.SRE_Match object at 0x02027288>
>>> n ='ba[r|z|d]', 'bas')

If not, it will return None

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

And just to print it to demonstrate again:

>>> print n
Answered By: James R

Here’s a function that does what you want:

import re

def is_match(regex, text):
    pattern = re.compile(regex)
    return 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.


>>> is_match('ba[rzd]', 'foobar')
>>> is_match('ba[zrd]', 'foobaz')
>>> is_match('ba[zrd]', 'foobad')
>>> is_match('ba[zrd]', 'foobam')
Answered By: kylan

The best one by far is

bool('ba[rzd]', 'foobarrrr'))

Returns True

Answered By: Venu Murthy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.