I'm creating a simple application and for one portion I would like to take the user's input from a TextCtrl and check if it is a valid URL. I've made this program without a GUI and used the following code: (I've changed it to use wxPython Error Dialogs but before I just printed out an error statement)
try:
if url[:7] != 'http://':
urllib.urlopen('http://' + url)
else:
urllib.urlopen(url)
except IOError:
error = wx.MessageDialog(None, 'Please enter a valid URL!', 'URL Error', wx.OK | wx.ICON_ERROR)
error.ShowModal()
When I run this code on a button click, the program freezes and crashes. I assume this is because it is interrupting the GUI's main loop. I guess I could try and validate the URL through if statements but I'm looking for something more efficient...possibly regex (although I have never learned regex).
Any help would be greatly appreciated.
Edit: This problem has been solved. I ended up using the regex used by Django:
def is_valid_url(url):
import re
regex = re.compile(
r'^https?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
return url is not None and regex.search(url)
Although it is not perfect, it worked for my case. Thanks!