2013-05-30 33 views
1

代碼:從URL找到網絡位置典雅

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,如果使用正則表達式,如何處理它。

+1

你有一個工作pythonic解決方案,並希望寫一個正則表達式來做同樣的 - 是否正確? –

+0

是的,謝謝你的提示 – liuzhijun

+2

問題是你需要一個TLD列表才能使其工作。例如,'foo.bar.com.br'中的netloc是什麼?反對'foo.bar.com'。沒有有效的頂級域名列表,沒有辦法讓所有頂級域名都能正常工作。 – Wolph

回答

0

說明

此正則表達式將驗證的URL包含任何try.github.iogethub.com

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

enter image description here

我不知道蟒蛇,所以我提供一個php例子來展示正則表達式的工作原理。

<?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]返回的值。