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

(singke) #1
After the phone exchange number, you must again match either a space, a dash, or a
dot:
( |-|\.)
Then to finish things off, you must match the four-digit local phone extension at the
end of the string:
[0-9]{4}$
Putting the entire pattern together results in this:
Click here to view code image
^\(?[2-9][0-9]{2}\)?(| |-|\.)[0-9]{3}( |-|\.)[0-9]{4}$


  1. Now that you have a regular expression, plug it into your code by opening a text
    editor and entering this code:
    Click here to view code image
    #!/usr/bin/python3


import re
pattern = re.compile(r'^\(?[2-9][0-9]{2}\)?(| |-|\.)[0-9]{3}( |-|\.)[0-9]
{4}$')

while(True):
phone = input('Enter a phone number:')
if (phone == 'exit'):
break
if (pattern.search(phone)):
print('That is a valid phone number')
else:
print('Sorry, that is not a valid phone number')
print('Thanks for trying our program')


  1. Save the file and exit the text editor.

  2. Run the file from the Raspberry Pi command prompt or the LXTerminal program in
    your window:
    Click here to view code image
    pi@raspberrypi ~ $ python3 script1601.py
    Enter a phone number:(555)555-1234
    That is a valid phone number
    Enter a phone number:333.123.4567
    That is a valid phone number
    Enter a phone number: 1234567890
    Sorry, that is not a valid phone number
    Enter a phone number:exit
    Thanks for trying our program
    pi@raspberrypi ~ $
    This is all there is to it! The script matches the input value against the regular
    expression pattern and displays the appropriate message.


Summary


If you manipulate data in Python scripts, you need to become familiar with regular expressions. A
regular expression defines a pattern template that’s used to filter text in a string value. The pattern

Free download pdf