Pattern Matching with Regular Expressions
175
The
r'^\d+$'
regular expression string matches strings that both begin
and end with one or more numeric characters. Enter the following into the
interactive shell:
>>>
wholeStringIsNum = re.compile(r'^\d+$')
>>>
wholeStringIsNum.search('1234567890')
>>> wholeStringIsNum.search('12345xyz67890') == None
True
>>> wholeStringIsNum.search('12 34567890') == None
True
The last two
search()
calls in the previous interactive shell example
demonstrate how the entire string must match the regex if
^
and
$
are used.
I always confuse the meanings of these two symbols, so I use the mne-
monic “Carrots cost dollars” to remind myself that the caret comes first and
the dollar sign comes last.
Dostları ilə paylaş: