Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

consists of a combination of standard text characters and special characters. The regular expression
engine uses the special characters to match a series of one or more characters. Python uses the re
module to provide a platform for using regular expressions in Python scripts. You can use the
match(), search(), findall(), and finditer() functions to filter text from string values
in your Python scripts using regular expression patterns.


In the next hour, we’ll take a look at how to use exceptions in your Python code. With exceptions, you
can add code to your program to handle if things go wrong while the program is running!


Q&A


Q. Do regular expressions work in all language characters?
A. Yes, because Python uses Unicode strings, you can use characters from any language in your
regular expression patterns.
Q. Is there a source for common regular expressions?
A. The http://www.regular-expressions.info website contains lots of different expressions for matching
all sorts of data!
Q. Can I save a regular expression test to use in other programs?
A. Yes, you can create a function (see Hour 12, “Creating Functions”) that checks text using your
regular expression. You can then copy the function into a module and use that in any program
where you need to validate that type of data!

Workshop


Quiz


1. What regular expression character matches text at the end of a string?
a. the caret (^)
b. the dollar sign ($)
c. the dot (.)
d. the question mark (?)
2. The caret special character performs the same function in a regular expression as the
match() Python function. True or false?
3. What regular expression pattern should you use to match both the words Charlie and
Charles?

Answers


1. b. The dollar sign ($) anchors the expression at the end of the string.
2. True. You may find it easier to use the match() Python function; however, there are plenty of
standard regular expressions that use the caret. You can use either format to accomplish the
same thing!
3. 'Charl[ie]+[es]+' This regular expression will match if either the "ie" or "es"
characters are at the end of the "Charl" string.
Free download pdf