Python re: return True if regex contains a string

I have a regex:

regexp = u'ba[r|z|d]' 

The function should return True if the word contains a bar , baz or bad . In short, I need a regular Python equivalent

 'any-string' in 'text' 

How can I understand that? Thank!

+79
python regex
Jan 25 '12 at 23:32
source share
5 answers
 import re word = 'fubar' regexp = re.compile(r'ba[rzd]') if regexp.search(word): print 'matched' 
+126
Jan 25 2018-12-23T00:
source share

The best of them is

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

Returns true

+89
Apr 01 '13 at
source share

Match objects are always true, and None returned if there is no match. Just experience the truth.

the 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 said, if st = foo bar , than a match will not work. Thus, it is more appropriate to use re.search .

+14
Jan 25 2018-12-12T00:
source share

Here is a function that does what you want:

 import re def is_match(regex, text): pattern = re.compile(regex, text) return pattern.search(text) is not None 

The regex search method returns an object with success and None if the pattern is not found in the string. With that in mind, we return True while the search returns us something.

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 
+1
Jan 25 2018-12-23T00:
source share

You can do something like this:

Using search will return an SRE_match 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, he 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 print it to demonstrate again:

 >>> print n None 
0
Jan 25 2018-12-23T00:
source share



All Articles