-1

I'm teaching myself Python with "Automate the Boring Stuff with Python" and I'm a bit confused by a code found in the book.

>>> wholeStringIsNum = re.compile(r'^\d+$')
>>> wholeStringIsNum.search('1234567890')
<re.Match object; span=(0, 10), match='1234567890'>
>>> wholeStringIsNum.search('12345xyz67890') == None
True
>>> wholeStringIsNum.search('12  34567890') == None
True

The strings passed to the last two search() methods seems to fit the regular expression, as the strings both begin and end with one or more digit, so why wouldn't I get back a matched object instead of none? The book says that if the caret symbol and dollar sign are in the regular expression, then the string passed in the method needs to fit the regular expression pattern exactly, but I don't understand why this is, if the pattern of the regular expression seems to be followed.

khelwood
  • 55,782
  • 14
  • 81
  • 108
FarRoutine
  • 67
  • 1
  • 3

1 Answers1

0

For the intended application use

^\d.*\d$
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55