【问题标题】:Regex not matching URL in Python [duplicate]Python中的正则表达式不匹配URL [重复]
【发布时间】:2023-03-13 20:31:01
【问题描述】:

可能重复:
how to extract domain name from URL

我想从一个 URL 中提取网站,即从以下 URL 中提取 console.aws.amazon.com

>>> ts
'https://console.aws.amazon.com/ec2/home?region=us-east-1#s=Instances,EC2 Management Console,12/3/2012 4:34:57 PM,11,0,,25806'
>>> re.match(ts,'(")?http(s)?://(.*?)/').group(0)

Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
re.match(ts,'(")?http(s)?://(.*?)/').group(0)
AttributeError: 'NoneType' object has no attribute 'group'

tried this regular expression in JS 成功了。知道为什么这在 JS 中匹配,但在 Python 中不起作用?

【问题讨论】:

  • Regex 或 regexp 如果你喜欢,但不是 regex。 Reg 普通 Ex 压力的缩写。
  • 投票重新打开 - 因为这个特定问题要求使用正则表达式来提取域。答案下方的评论阐明了为什么 urlparse 不理想在这种情况下 - 即将导出一个 exe,并且包含的​​越少越好。

标签: python regex


【解决方案1】:

您总是可以为此使用str.partition 方法:

print(ts.partition('//')[2].partition('/')[0])
>>> console.aws.amazon.com

正则表达式对此有点矫枉过正。

【讨论】:

  • 即使您的解决方案也有点矫枉过正,因为 urlparse 模块的存在正是这个目的。
【解决方案2】:

你的比赛不正确。 Python doco 说的:

re.match(pattern, string, flags=0)

你正在做:

re.match(string, pattern)

所以只需将其更改为:

 re.match('(")?http(s)?://(.*?)/', ts).group(0)

【讨论】:

  • 好的,这就是根本原因。 :)
  • 很高兴你解决了它;)尽管使用像下面的窥视者这样的现有工具绝对是你应该看看的东西。如果已经存在,不要自己写东西;)
  • 如果你建议“如果已经存在就不要自己写东西”,那你为什么要鼓励它呢?
  • 因为它是解决问题的方法。另一个答案是肖恩所遇到问题的替代方案(不是解决方案)。
  • 虽然它是 a 解决方案,但@ShawnZhang 应该使用 urlparse,它旨在恰好达到此目的,而不是通过一些复杂的正则表达式由随机的互联网用户开发。
【解决方案3】:

使用urlparse

>>> from urlparse import urlparse
>>> u = 'https://console.aws.amazon.com/ec2/home?region=us-east-1#s=Instances,EC2 Management Console,12/3/2012 4:34:57 PM,11,0,,25806'
>>> p = urlparse(u)
>>> p
ParseResult(scheme='https', netloc='console.aws.amazon.com', path='/ec2/home', params='', query='region=us-east-1', fragment='s=Instances,EC2 Management Console,12/3/2012 4:34:57 PM,11,0,,25806')
>>> p.netloc
'console.aws.amazon.com'
>>> 

【讨论】:

  • +1 的好建议
猜你喜欢
  • 2015-09-14
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多