0

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!

Rev22
  • 27
  • 1
  • 3
  • seems to work fine for me ... it takes a while to come back negative but as long as it raises the error i see the dialog ... (I tried :http://blaaalaala.com/) – Joran Beasley Nov 27 '12 at 23:51
  • @JoranBeasley It works fine without a GUI, but when I use it with wxPython it freezes and crashes the program. – Rev22 Nov 28 '12 at 06:13
  • then you should post a complete example that demonstrates your problem in the minimum number of lines you can – Joran Beasley Nov 28 '12 at 06:45

1 Answers1

0

That should work, but if you want to go the regex route, see the following answer: How do you validate a URL with a regular expression in Python?

I think you could combine that information with a MaskedEditControl. The wxPython demo has lots of examples.

Community
  • 1
  • 1
Mike Driscoll
  • 32,629
  • 8
  • 45
  • 88