2010-02-18 47 views
0

我在編寫正則表達式時遇到了一些困難。我的投入將是一個URL,看起來像這樣:捕獲網址的一部分

http://www.a.com/farms/important-stuff-here#ignorable-stuff

我想捕捉(一些-的東西,在這裏),這是最後的斜線之間的一切,和第一#符號(或只是。結束,如果#標誌額外內容不存在我想這可能做到這一點:

(http://www.a.com/farms/)
([anything but a # character]*)
(.*)

我不知道如何expre第二組([anything but a # character]*)。

感謝

+0

我正在使用java。 – user246114 2010-02-18 03:46:54

回答

1

「任何事情,但」被稱爲否定字符類,並在你的情況下,拼

[^#] 

你的正則表達式將是

http://www.a.com/farms/([^#]+) 
1

對於大多數重新你可能要[^#]引擎(該^否定字符類)。

0

取決於你的語言,你可能想使用模塊/庫,可以很好地解析你的網址。例如,在PHP中,你可以使用parse_url

$url = "http://www.a.com/farms/important-stuff-here#ignorable-stuff"; 
$parsed = parse_url($url); 
print $parsed['path']; 

與Python,urlparse()如:

>>> import urlparse 
>>> s=""http://www.a.com/farms/important-stuff-here#ignorable-stuff" 
>>> urlparse.urlparse(s).path 
'/farms/important-stuff-here' 

如果你真的想通過做手工,第一取代一切從「#」開始,然後取代一切從一開始,直到上串 「/」

$ echo "http://www.a.com/farms/important-stuff-here#ignorable-stuff" | sed 's/#.*//;s|.*\/||' 
important-stuff-here 

或者使用只是普通的分裂

$url = "http://www.a.com/farms/important-stuff-here#ignorable-stuff"; 
$s = explode("#",$url,2); 
$t = explode("/",$s[0]); 
print end($t); 
+0

不會在path()中包含「farm /」嗎?我只想[重要的東西在這裏],謝謝。 – user246114 2010-02-18 03:48:40

+0

這很容易修復。爆炸/拆分「/」並獲得正確的項目。我會讓你自己做。 – ghostdog74 2010-02-18 04:22:36