【发布时间】:2015-06-17 00:39:15
【问题描述】:
给定一个 URL,我必须使用正则表达式来查找主机名。
网址可以有多种形式:
http://www.google.com/ [expected 'google.com']
https://www.google.com:2000/ [expected 'www.google.com']
http://100.1.25.3:8000/foo/bar?abc.php=xxxx+xxxx [expected '100.1.25.3']
www.google.com [expected 'www.google.com']
10.0.2.2:5000 [expected '10.0.2.2']
localhost/ [expected 'localhost']
localhost/foo [expected 'localhost']
我能想到的最接近的是:
^(?:[^:]+://)*([^:/]+).*
并使用正则表达式的第一个捕获组捕获的字符串。
但是,有些情况会失败:
google.com [nothing is captured, expected 'google.com']
http://///x ['http' is captured, expected nothing]
什么是可以处理这些情况的正则表达式?
请注意:
- 我不是在问我的正则表达式有什么问题。我知道哪里出了问题,我就是想不出另一个正则表达式。
- 解决方案只需要可靠地提取主机名,无需验证它。我稍后会验证这些东西,所以如果正则表达式从
https://google!com/foo中取出google!com,这是可以接受的*。
* ... 甚至可能是可取的,因为主机名可以包含 Unicode 字符(国际化域名)。
【问题讨论】:
-
也显示您的预期输出。
-
为什么不使用 uri 处理库呢? re 绝对不是一个合适的工具:mathiasbynens.be/demo/url-regex