从URL优雅地查找网络位置

2024-03-29 10:43:39 发布

您现在位置:Python中文网/ 问答频道 /正文

代码:

import urlparse
url1 = 'http://try.github.io//levels/1/challenges/1'
netloc1 = urlparse.urlparse(url1)[1]  #try.github.io

url2 = 'https://github.com/explore'
netloc2 = urlparse.urlparse(url2)[1]  #github.com

netloc2是我想要的,但是我希望netloc1github.io,如果使用regex,如何处理。你知道吗


Tags: 代码httpsioimportgithubcomhttplevels
1条回答
网友
1楼 · 发布于 2024-03-29 10:43:39

说明

此正则表达式将验证url的包含try.github.iogethub.com

^https?:[\/]{2}(try[.]github[.]io|github[.]com)

enter image description here

示例

我不懂python,所以我提供了一个php示例来展示regex是如何工作的。你知道吗

<?php
$sourcestring="your source string";
preg_match_all('/^https?:[\/]{2}(try[.]github[.]io|github[.]com)/im',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>

$matches Array:
(
    [0] => Array
        (
            [0] => http://try.github.io
            [1] => https://github.com
        )

    [1] => Array
        (
            [0] => try.github.io
            [1] => github.com
        )

)

免责声明

使用urlparse解决方案,然后应用一些逻辑来测试[1]返回值可能更容易。你知道吗

相关问题 更多 >