Razz Abuiss
Razz Abuiss

Reputation: 53

Strings containing $ not being found in Python

I ran in to an unexpected difficulty with regular expression matching in python: As expected:

>>> re.match("r", "r").group() #returns...
"r"

However:

>>>re.match("r", "$r").group()
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

Does anybody know why the dollar sign causes trouble when it's in the string to be matched, and how I can fix this?

Upvotes: 0

Views: 79

Answers (1)

dawg
dawg

Reputation: 104102

Look at the difference between re.match and re.search

>>> re.match("r", "$r")    # no match since re.match is equivalent to '^r'
>>> re.search("r", "$r")   # match
<_sre.SRE_Match object at 0x10047d3d8>

re.match searches from the BEGINNING of the string, so "r" does not match "$r" because "$r" does not start with 'r'.

re.search scans through the string, so it is not dependent on the start of the string.

As a general form, you should do matching this way:

match=re.search(pattern, string)
if match
   # you have a match -- get the groups...
else:
   # no match -- deal with that...

Upvotes: 4

Related Questions