0

I am learning python with the online book automate the boring stuff. In chapter7 they say that the expression ^\d+$ evaluates to 'all characters must be digits' but i don't understand this. Earlier in the chapter it is said that the ^ symbol stands for (string will match if it starts with the specified character(set)) which is \d in this case. The + symbol means it must have one or more digits and then the dollar sign means that it should end with one or more digits. They give the following code as example.

Please see below:

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

Shouldn't the two expressions that evaluate to True in the example actually be False? I mean they both start and end with one or more digits.

Please explain,

Thanks

FAM_Maurice
  • 193
  • 6
  • 1
    How do you expect `12345xyz67890` to be true if there is no letter matching pattern in the `^\d+$` regex? You yourself see/write it matches only digits between string start and end. To starts and end with digits, it should have been `(?s)^\d.*\d$` – Wiktor Stribiżew Aug 09 '19 at 07:41
  • First string contains letters so will not match any regex that does not include letters. As the Regex also does not include white space, the second string will not be matched either. – Gustav Rasmussen Aug 09 '19 at 07:44
  • 1
    Also, learn to use Regex101 debugger, you could quickly [see with your own eyes why it does not match](https://regex101.com/r/GKJYY2/1/debugger) what you expected. – Wiktor Stribiżew Aug 09 '19 at 08:09
  • thats cool but could someone please tell me step by step what this regex does then? Explain it to me piece be piece please. – FAM_Maurice Aug 09 '19 at 08:11

0 Answers0