177

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!

3
  • 32
    Just use bool(re.search('ba[rzd]', 'sometext')). Commented Jan 26, 2012 at 2:28
  • @RaymondHettinger why do you need bool? Commented Jul 7, 2021 at 16:25
  • @igorkf you can use bool for typing. e.g. def f(x: bool) -> bool: ... body etc cheers! Commented Jul 7, 2021 at 16:26

5 Answers 5

242
import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
  print('matched')
Sign up to request clarification or add additional context in comments.

3 Comments

I am working on a similar case where I want to search for an exact string (xyz) and want to know which is a more efficient way to do this, should I use python's 'xyz' in given_text or use re.compile(r'xyz').search(given_text) ?
the [] brackets contain a character class, so your re also matches: >>> word = 'ba|'; regexp.search(word) <_sre.SRE_Match object at 0x101030b28> . You can drop all the pipe symbols.
why do you need the r in front of your string? i.e. what is the difference between re.compile(r'x[\d+]') vs re.compile('x[\d+]')?
169

The best one by far is

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

Returns True

4 Comments

Why is this one better than the other solutions?
For one thing, it returns a bool. OP: "must return True if word contains bar, baz or bad." Other answers use the behavior of if - auto-converting the expression to its right to a bool. e.g. import re; rgx=re.compile(r'ba[rzd]'); rgx.search('foobar') => <re.Match object; span=(2, 5), match='bar'>, but if(rgx.search(w)): print('y') => y. Closest to documentation of auto-convert I could find(archived)
why did you prefer .search vs .match?
also why did you not use r infront of the regex e.g. re.compile(r'x[\d+]') vs re.compile('x[\d+]')?
25

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.

4 Comments

As I understand the question, OP actually wants search rather than match. (See docs.python.org/library/re.html#matching-vs-searching.) Also, I think it would be helpful if you showed actual possible arguments, in the correct order, rather than just ....
if you change st to "foo bar", the match method will not work here. You want search.
@ruakh that link no longer auto scroll to that part of the doc, now the link is docs.python.org/2/library/re.html#search-vs-match
@RanRag what is the complexity difference in searching substring with in and regex?
4

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.