This is yet another project using regular expressions that will help us find all phone numbers and emails on a page which is posted in the clipboard; the search result will be put in to the clipboard as a string. To start, we need to import the libraries that we need – in this case re and pyperclip (which can help us interact with the clipboard)
import pyperclip, re
We also need to determine the date types of the info that we will be processing, so its always useful to create a simple note to remember that.
# input: - multi line str in clipboard
# ouput: -matched objects in clipboard (str)
The most important step is to create the regexes. The phone regex is quite simple, but the email proved to be a conundrum.
phoneRegex = re.compile(r'''(
(\d{3}|\(\d{3}\))? # area code
(\s|-|\.)? # separator
(\d{3}) # first 3 digits
(\s|-|\.) # separator
(\d{4}) # last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? #extension
)''', re.VERBOSE)
emailRegex = re.compile(r'''(
([-~\w]+) #username
@
(([-~\w]+\.)+[-~\w]+) #domain name
)''', re.VERBOSE)
Next, the found text is pastes in to the clipboard. The email regex is already formatted properly, but since the phone numbers can be formatted in different ways, we have to make sure they are copied down the same way for our convenience.
text = str(pyperclip.paste())
matches = []
for groups in emailRegex.findall(text):
matches.append(groups[0])
for groups in phoneRegex.findall(text):
phone_num = '-'.join([groups[1], groups[3], groups[5]])
if groups[8] != '': phoneNum += ' x' + groups[8]
matches.append(phone_num)
Finally, if any contact information is found, we copy them in to the clipboard whilst displaying text that we have done so.
#copy results to clipboard
if len(matches) > 0:
pyperclip.copy('\n'.join(matches))
print("Copied to clipboard:")
print('\n'.join(matches))
else:
print('No phone numbers or email adresses found :/')