This is a problem from Automate the Boring Stuff from "Pattern Matching with Regular Expression". I am a beginner in Python and the purpose of this program is to match urls which start with http://
or https://
, with some urls having an optional www.
after https://
How can this code be improved?
#! /usr/bin/python3
#websiteURL.py - Find website URLs that begin with http:// or https://
import pyperclip, re
#protocol Regex - checks for http:// or https://
protocolRegex = re.compile(r'''
https?:// #match http:// or https://
(?:w{3}\.)? #www-dot
[a-zA-Z0-9_-]+ #domin name
\. #dot
[a-zA-Z]{2,3} #extension
''', re.VERBOSE)
text = str(pyperclip.paste()) #copying data from document to clipboard and converting it into a string
matches = [] #stores all matches in this list
for website in protocolRegex.findall(text): #finding website from the string text
matches.append(website)
if len(matches) > 0:
pyperclip.copy('\n'.join(map(str, matches))) #copying result to clipboard after adding newline after each match
print('Copied to clipboard:')
print('\n'.join(matches))
else:
print('No website found')
Running code:
chmod +x websiteURL.py
./websiteURL.py
http://www.example.co.uk
is not a valid URL? \$\endgroup\$findall
and notmatch
, right. But this is confusing from the regex alone… \$\endgroup\$