2012-04-18 104 views
0

我正在瀏覽twitter bootstrap的代碼,並且我幾次都在昏迷這段代碼。這個JavaScript的正則表達式替換空白嗎?

href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 

正則表達式是我的盲點,我找不出它們中的大多數。什麼是替代? #之後是否有空格?

附註。任何人都可以推薦正則表達式學費的好來源?

+3

側回答:HTTP://www.regular-expressions。 info/ – musefan 2012-04-18 14:04:40

回答

6

這裏就是它的尋找:

.*  # any number of characters (optional) 
(?= # open a lookahead 
#  # find a hash tag 
[^\s]+ # at least one non-whitespace character 
$  # end of line 
)  # close the lookahead 

因此,舉例來說,它匹配的哈希標籤之前會發生什麼:

replace this!#foobar <-- matches: replace this! 
hello world#goodbye <-- matches: hello world 
no match here !  <-- doesn't match anything because there is no hash 
what?#     <-- does not match because there is nothing after the hash 
what?# asd    <-- does not match because there is a whitespace-character 
+0

有效和無效匹配的幾個例子會很好地回答;) – musefan 2012-04-18 14:08:26

+0

@musefan好主意。我會拋出一些。 – alan 2012-04-18 14:08:58

+1

注'+'匹配1或更多 – Christoph 2012-04-18 14:10:00