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

Question:

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

||

Answers:

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.

Answered By: RanRag
import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
  print('matched')
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 = re.search(u'ba[r|z|d]', 'bar')
>>> m
<_sre.SRE_Match object at 0x02027288>
>>> m.group()
'bar'
>>> n = re.search(u'ba[r|z|d]', 'bas')
>>> n.group()

If not, it will return None

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

And just to print it to demonstrate again:

>>> print n
None
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 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
Answered By: kylan

The best one by far is

bool(re.search('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.