Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regexp是否从链接获取网站名称?_Regex_Sed - Fatal编程技术网

Regexp是否从链接获取网站名称?

Regexp是否从链接获取网站名称?,regex,sed,Regex,Sed,我试图从链接中获取网站名称,例如,如果给定链接是 http://www.example.com/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip 我只想从www.example.com中解脱出来。链接有数百个,所以手工工作是无用的。因此,我使用sed之类的东西尝试regexp 有人能帮忙吗?试试这个://\/{2}.*?\//它会找到//和//之间的任何东西,这可以: sed -r 's|(.*://)?([^/]*).*|\2

我试图从链接中获取网站名称,例如,如果给定链接是

http://www.example.com/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip
我只想从www.example.com中解脱出来。链接有数百个,所以手工工作是无用的。因此,我使用sed之类的东西尝试regexp

有人能帮忙吗?

试试这个://\/{2}.*?\//它会找到//和//

之间的任何东西,这可以:

sed -r 's|(.*://)?([^/]*).*|\2|' file
它处理带有和不带http/ftp的URL…:

使用GNU grep:

grep -oP '(?<=//)[^/]*' <<<"$url"
再试试这个

$ sed 's/^http:\/\/\([^/]*\).*/\1/g' file
www.example.com

您可以使用Perl模块,而不是使用正则表达式。假设链接列表位于名为links的文件中,这将打印出所有主机名:

perl -MURI::URL -ne '$url = url $_; print $url->host' links
样本输入:

http://www.example.com/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip                                                                                                                               
http://www.other.example.org/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip                                                                                                                         
http://www.third.net/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip
输出:

www.example.com
www.other.example.org
www.third.net
使用grep工具例如


虽然其他答案也解决了这个问题,但我之所以选择这个答案,是因为一个未知的原因:PHahhaah就是这样一个原因,@RegisteredUser:D@fedorqui谢谢我喜欢那些前卫和后卫。有一个断言的想法,但不包括在比赛中是伟大的!感谢perl开发人员!不幸的是,它们仅在GNU grep中可用。BSD grep知道选项-P,但只是输出。。。不支持它们非常方便,我不久前在这里发现了它们。。。不得不越来越多地使用它们。不知道BSD上没有。从我所看到的来看,这意味着例如OSX不能使用它们。太糟糕了…@fedorqui是的,不幸的是,所有BSD变体,如OSX,都不能使用-P,除非GNU grep安装在该系统上。这是可能的。我希望看到一些GNU扩展获得POSIX标准,因为它们是有意义的,但我想这真的很难实现。至少比开发扩展更难:
http://www.example.com/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip                                                                                                                               
http://www.other.example.org/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip                                                                                                                         
http://www.third.net/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip
www.example.com
www.other.example.org
www.third.net
echo 'http://www.example.com/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip' | grep -o 'http://[a-zA-Z0-9.-]*/'