如何使用python从字符串中提取网址? [英] How do you extract a url from a string using python?

查看:916
本文介绍了如何使用python从字符串中提取网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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

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

How could I extract 'http://www.google.com' ?

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

(Each link will be of the same format i.e 'http://')

推荐答案

执行此操作的方法可能很少,但最干净的方法是使用正则表达式

There may be few ways to do this but the cleanest would be to use regex

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

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

If there can be multiple links you can use something similar to below

>>> 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']
>>> 

这篇关于如何使用python从字符串中提取网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆