【发布时间】:2019-07-22 20:10:32
【问题描述】:
如果我有一个字符串,则前面总是有http://,并且可选地后面是/。示例:
http://www.mymovies.com/
但有时可以采用以下格式: http://www.mymovies.com
我要提取www.mymoviews.com
我想捕获两种格式(有/没有/)
我尝试使用:
import re
print(re.search('http://(.*)/','http://www.mymovies.com').group(1))
但我收到此错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
1) 如何解决错误
2)如何捕获有/没有以下/字符(因为我的解决方案需要/
【问题讨论】:
-
re.search('www.+com',s).group() -
正如我在问题中所说的那样,
www.我的固定字符并不总是http://。 -
试试
http://([^/]*)/?,见this regex demo -
@Wiktor Stribiżew 如何尝试?使用重新?你能写出整行吗?
-
是的,
re就足够了。print(re.search(r'http://([^/]*)/?','http://www.mymovies.com').group(1))和print(re.search(r'http://([^/]*)/?','http://www.mymovies.com/').group(1))。我不知道你想匹配什么其他类型的 URL,因此,这是一个建议。
标签: python regex python-3.x string search