pythons re: return True if string contains regex pattern

pythons re: return True if string contains regex pattern

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

The best one by far is

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

Returns True

pythons re: return True if string contains regex pattern

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

Code:

>>> st = bar
>>> m = re.match(rba[r|z|d],st)
>>> if m:
...     m.group(0)
...
bar

Output = bar

If you want search functionality

>>> st = bar
>>> m = re.search(rba[r|z|d],st)
>>> if m is not None:
...     m.group(0)
...
bar

and if regexp not found than

>>> st = hello
>>> m = re.search(rba[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.

Leave a Reply

Your email address will not be published. Required fields are marked *