0

我正在创建一个简单的应用程序,其中一部分我想从 TextCtrl 获取用户的输入并检查它是否是有效的 URL。我在没有 GUI 的情况下制作了这个程序并使用了以下代码:(我已将其更改为使用 wxPython 错误对话框,但在我刚刚打印出错误语句之前)

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()

当我单击按钮运行此代码时,程序冻结并崩溃。我认为这是因为它中断了 GUI 的主循环。我想我可以尝试通过 if 语句验证 URL,但我正在寻找更有效的东西……可能是正则表达式(尽管我从未学过正则表达式)。

任何帮助将不胜感激。

编辑:这个问题已经解决了。我最终使用了 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)

虽然它并不完美,但它适用于我的情况。谢谢!

4

1 回答 1

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.

于 2012-11-28T14:27:11.897 回答