2012-03-15 99 views
1

我正在開發一個http機器人,並且我開發了這個正則表達式 (((?:f|ht)tp(?:s)?\\://)?|www)([^/]+)來檢測並從鏈接(href)中提取主機名。 現在我把這裏的測試結果:正則表達式主機名

String -> http://www.meloteca.com/empresas-editoras.htm 
Returns http://www.meloteca.com 
String -> www.meloteca.com/empresas-editoras.htm  
Returns www.meloteca.com 
String -> /empresas-editoras.htm 
Returns empresas-editoras.htm (without the slash) 

在這種情況下,我期待的是,正則表達式不返回任何值?這是爲什麼發生? 同樣的事情,如果我嘗試用下面的代碼串

String -> empresas-editoras.htm 
Returns empresas-editoras.htm 

的片段:

Pattern padrao = Pattern.compile("(((?:f|ht)tp(?:s)?\\://)?|www)([^/]+)"); 
     Matcher mat = padrao.matcher("empresas-editoras.htm"); 
     if(mat.find()) 
      System.out.println("Host->"+mat.group()); 

回答

3

它最好能夠使用URI類,它的方法,如getHost()getPath(),而比正則表達式。構建URIs的規則比你可能意識到的要複雜得多,而你的正則表達式可能會有很多不正確處理的角落案例。

1

如果去掉問號之一,像這樣:

(((?:f|ht)tp(?:s)?\\://)|www)([^/]+) 

它應該更好地工作。

0

替代((?:f|ht)tp(?:s)?\\://)?是可選的,所以它可以是空字符串,然後([^/]+)只是匹配任何不包含/的字符串。