【问题标题】:how to validate only http:// or https:// starting urls using python如何使用 python 仅验证 http:// 或 https:// 起始 url
【发布时间】:2019-01-23 08:47:12
【问题描述】:

我的代码:

import re
url=input("enter the url")
match_obj=re.match( r'^(?:http)s?://',url,re.I|re.M)
if match_obj:
    print("valid url",match_obj.group())
else:
    print("invalid url")

有没有更好的方法?

【问题讨论】:

  • 这段代码有什么问题?
  • 对 http:// 或 https:// 之后的内容有何限制?
  • 请解释您显示的代码有什么问题,一些关于如何使用它的示例以及预期的输出
  • 第 3 行 ?: 应该去掉,换成 http|https

标签: python url


【解决方案1】:

您可以使用str.startswith():而不是正则表达式:

url = input('Enter the url: ').lower()

if url.startswith(('http://', 'https://')):
    print('valid url')
else:
    print('invalid url')

【讨论】:

    【解决方案2】:

    试试这个:

    import re
    
    url=input("enter the url")
    regex = re.compile(r'https?:\/\/([^\/]*)')
    regObj = regex.findall(url)
    if regObj :
        print("valid url")
    else:
        print("invalid url")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      相关资源
      最近更新 更多