2012-04-18 105 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