161

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!

Makogan
  • 8,208
  • 7
  • 44
  • 112
ghostmansd
  • 3,285
  • 5
  • 30
  • 44

5 Answers5

225
import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
  print('matched')
mattbornski
  • 11,895
  • 4
  • 31
  • 25
  • 1
    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)` ? – bawejakunal May 04 '16 at 09:01
  • 1
    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. – radtek Jan 27 '17 at 14:51
  • 2
    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+]')`? – Charlie Parker Jul 07 '21 at 16:25
162

The best one by far is

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

Returns True

Venu Murthy
  • 2,064
  • 1
  • 15
  • 13
  • 2
    Why is this one better than the other solutions? – Kresten May 16 '19 at 18:29
  • 4
    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')` => ``, but `if(rgx.search(w)): print('y')` => `y`. [Closest to documentation of auto-convert I could find](http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/boolean.html)([archived](https://web.archive.org/web/20200319164133/http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/boolean.html)) – bballdave025 Mar 19 '20 at 16:57
  • 1
    why did you prefer `.search` vs `.match`? – Charlie Parker Jul 07 '21 at 16:28
  • also why did you not use `r` infront of the regex e.g. `re.compile(r'x[\d+]')` vs `re.compile('x[\d+]')`? – Charlie Parker Jul 07 '21 at 16:28
21

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.

RanRag
  • 48,359
  • 38
  • 114
  • 167
  • 1
    As I understand the question, OP actually wants `search` rather than `match`. (See http://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 `...`. – ruakh Jan 25 '12 at 23:37
  • 1
    if you change `st` to `"foo bar"`, the match method will not work here. You want search. – bukzor Jan 25 '12 at 23:45
  • @ruakh that link no longer auto scroll to that part of the doc, now the link is https://docs.python.org/2/library/re.html#search-vs-match – freeforall tousez Nov 17 '14 at 22:12
  • @RanRag what is the complexity difference in searching substring with `in` and `regex`? – Piyush S. Wanare Oct 13 '17 at 13:48
3

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
chrimaho
  • 580
  • 4
  • 22
kylan
  • 513
  • 1
  • 4
  • 8
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
James R
  • 4,571
  • 3
  • 30
  • 45