Terrence Brannon
Terrence Brannon

Reputation: 4968

no match returned for this regular expression

I am using raw string notation to express a fairly simple regular expression and I am not getting a match object. Shell transcript follows:

[~/Documents/Programming/rlm]$ python
python
Python 2.7.5 (default, Aug 25 2013, 00:04:04) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> s = 'bob2323'
s = 'bob2323'
>>> import re
import re
>>> re.match(r'\d+', s)
re.match(r'\d+', s)
>>> 

Upvotes: 0

Views: 194

Answers (2)

Charles Salvia
Charles Salvia

Reputation: 53289

You need to use re.search. re.match only attempts to match starting at the beginning of the string. However, re.search will search through the entire string looking for a substring that matches the pattern.

>>> import re
>>> s = "bob2323"
>>> re.match(r'\d+', s)
>>> re.search(r'\d+', s)
<_sre.SRE_Match object at 0x7f4d19beb988>
>>> 

See search() vs. match() in the docs for more information

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

Use re.search instead of re.match, because re.match only matches from the start of the string.:

>>> re.search(r'\d+', s)
<_sre.SRE_Match object at 0xb5eefbf0>

re.match vs re.search:

re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string.

Upvotes: 2

Related Questions