如何使用python从字符串中提取网址?

发布于 2021-01-29 19:31:59

例如:

string = "This is a link http://www.google.com"

如何提取“ http://www.google.com”?

(每个链接的格式都相同,即“ http://”)

关注者
0
被浏览
285
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    可能有几种方法可以做到这一点,但最干净的方法是使用正则表达式

    >>> myString = "This is a link http://www.google.com"
    >>> print re.search("(?P<url>https?://[^\s]+)", myString).group("url")
    http://www.google.com
    

    如果可以有多个链接,则可以使用类似于以下内容的链接

    >>> myString = "These are the links http://www.google.com  and http://stackoverflow.com/questions/839994/extracting-a-url-in-python"
    >>> print re.findall(r'(https?://[^\s]+)', myString)
    ['http://www.google.com', 'http://stackoverflow.com/questions/839994/extracting-a-url-in-python']
    >>>
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看