2009-02-06 17 views
0

我正在从我的网址中解压主机,并且由于最后/可选而陷入了僵局。 正则表达式需要准备接收下列内容:什么是最好的方式来提取正则表达式的网址的主机部分?

http://a.b.com:8080/some/path/file.txt 
or 
ftp://a.b.com:8080/some/path 
or 
ftp://[email protected]/some/path 
or 
http://a.b.com 
or 
a.b.com/some/path 

and return a.b.com 

所以......

(ftp://|http://)? optionally matches the first part 
then it gets hairy... 
so... without adding ugly (and wrong) regexp here... just in english 
(everything that isn't an '@') //optional 
(everything that isn't a '/' up to the first '/' IF it's there) //this is the host group that I want 
(everything else that trails) //optional 

回答

2

杰里米流转的的答案是接近,但如果@主机名之后出现在任何地方都将失败。我建议:

(一切,这是不是一个 '@')//可选

(?:[^ @:/ * @)?

如果在域后出现@,冒号和斜杠将阻止匹配通过域。请注意非捕获的parens。

(一切,是不是 '/' 到第一个 '/',如果它的存在) //这是主机组,我想

([^:/] +)

请注意捕获的parens。

(其他一切落后)//可选

由于括号捕获的主机名和唯一的主机名,就没有必要继续匹配。

所以,把他们放在一起,你得到:

/^(?:?FTP | HTTPS)://(?:[^ @:/ * @)([^:/] + )/

(请注意,前两个paren分组是非捕获 - 希望您的正则表达式库支持。)

5

你需要使用正则表达式?大多数语言都支持解析URL。例如,Java有它的java.net.URL,Python有它的urlparse模块,Ruby有它的URI模块。您可以使用它们来查询给定URL的不同部分。

0

我在PHP测试这一点,它适用于所有的例子:

/^(ftp:\/\/|https?:\/\/)?([email protected])?([a-zA-Z0-9\.\-]+).*$/