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

PythonRegex

Python Problem Overview


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!

Python Solutions


Solution 1 - Python

import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
  print('matched')

Solution 2 - Python

The best one by far is

bool(re.search('ba[rzd]', 'foobarrrr'))

Returns True

Solution 3 - Python

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.

Solution 4 - Python

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

Solution 5 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionghostmansdView Question on Stackoverflow
Solution 1 - PythonmattbornskiView Answer on Stackoverflow
Solution 2 - PythonVenu MurthyView Answer on Stackoverflow
Solution 3 - PythonRanRagView Answer on Stackoverflow
Solution 4 - PythonkylanView Answer on Stackoverflow
Solution 5 - PythonJames RView Answer on Stackoverflow