Pattern Matching with Regular Expressions
165
Creating Regex Objects
All the regex functions in Python are in the
re
module. Enter the following
into the interactive shell to import this module:
>>>
import re
N O T E
Most of the examples in this chapter will require the
re
module, so remember to import
it at the beginning of any script you write or any time you restart Mu. Otherwise,
you’ll get a
NameError: name 're' is not defined
error message.
Passing a string value representing your regular expression to
re.compile()
returns a
Regex
pattern object (or simply, a
Regex
object).
To create a
Regex
object that matches the phone number pattern, enter
the following into the interactive shell. (Remember that
\d
means “a digit
character” and
\d\d\d-\d\d\d-\d\d\d\d
is the regular expression for a phone
number pattern.)
>>>
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
Now the
phoneNumRegex
variable contains a
Regex
object.
Dostları ilə paylaş: