7 pat t e r n m at c h I n g w I t h r e g u L a r e X p r e s s I o n s


The Caret and Dollar Sign Characters



Yüklə 397,03 Kb.
Pdf görüntüsü
səhifə14/25
tarix29.11.2022
ölçüsü397,03 Kb.
#71308
1   ...   10   11   12   13   14   15   16   17   ...   25
P A T T E R N M A T C H I N G W I T H

The Caret and Dollar Sign Characters
You can also use the caret symbol (
^
) at the start of a regex to indicate that 
a match must occur at the beginning of the searched text. Likewise, you can 
put a dollar sign (
$
) at the end of the regex to indicate the string must end 
with this regex pattern. And you can use the 
^
and 
$
together to indicate 
that the entire string must match the regex—that is, it’s not enough for a 
match to be made on some subset of the string. 
For example, the 
r'^Hello'
regular expression string matches strings 
that begin with 
'Hello'
. Enter the following into the interactive shell:
>>> beginsWithHello = re.compile(r'^Hello')
>>> beginsWithHello.search('Hello, world!')

>>> beginsWithHello.search('He said hello.') == None
True
The 
r'\d$'
regular expression string matches strings that end with a 
numeric character from 0 to 9. Enter the following into the interactive shell:
>>> endsWithNumber = re.compile(r'\d$')
>>> endsWithNumber.search('Your number is 42')

>>> endsWithNumber.search('Your number is forty two.') == None
True


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.

Yüklə 397,03 Kb.

Dostları ilə paylaş:
1   ...   10   11   12   13   14   15   16   17   ...   25




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin