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


Making Your Own Character Classes



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

Making Your Own Character Classes
There are times when you want to match a set of characters but the short-
hand character classes (
\d

\w

\s
, and so on) are too broad. You can define 
your own character class using square brackets. For example, the character 
class 
[aeiouAEIOU]
will match any vowel, both lowercase and uppercase. Enter 
the following into the interactive shell:
>>> vowelRegex = re.compile(r'[aeiouAEIOU]')
>>> vowelRegex.findall('RoboCop eats baby food. BABY FOOD.')
['o', 'o', 'o', 'e', 'a', 'a', 'o', 'o', 'A', 'O', 'O']


174
Chapter 7
You can also include ranges of letters or numbers by using a hyphen. 
For example, the character class 
[a-zA-Z0-9]
will match all lowercase letters, 
uppercase letters, and numbers.
Note that inside the square brackets, the normal regular expression 
symbols are not interpreted as such. This means you do not need to escape 
the 
.

*

?
, or 
()
characters with a preceding backslash. For example, the 
character class 
[0-5.]
will match digits 
0
to 
5
and a period. You do not need 
to write it as 
[0-5\.]
.
By placing a caret character (
^
) just after the character class’s opening 
bracket, you can make a negative character class. A negative character class 
will match all the characters that are not in the character class. For example, 
enter the following into the interactive shell:
>>> consonantRegex = re.compile(r'[^aeiouAEIOU]')
>>> consonantRegex.findall('RoboCop eats baby food. BABY FOOD.')
['R', 'b', 'C', 'p', ' ', 't', 's', ' ', 'b', 'b', 'y', ' ', 'f', 'd', '.', ' 
', 'B', 'B', 'Y', ' ', 'F', 'D', '.']
Now, instead of matching every vowel, we’re matching every character 
that isn’t a vowel.

Yüklə 397,03 Kb.

Dostları ilə paylaş:
1   ...   9   10   11   12   13   14   15   16   ...   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