2011-08-19 23 views
1
每天的兩種嘗試

我在JavaScript中有下面的正則表達式:JavaScript正異常匹配字符串一旦在Chrome和Firefox

var the_regexp = /^\/([!\/]*)\/?(\w*)\??([\=|\w]*)\/?$/gi 

它Firefox和Chrome的控制檯,它找到字符串匹配「/ d」每兩次嘗試一次。

>the_regexp 
/^\/([!\/]*)\/?(\w*)\??([\=|\w]*)\/?$/gi 
>the_regexp.exec("/d") 
null 
>the_regexp.exec("/d") 
["/d", "", "d", ""] 
>the_regexp.exec("/d") 
null 
>the_regexp.exec("/d") 
["/d", "", "d", ""] 

有人可以解釋這種行爲嗎?

回答

4

MDN Docs

如果你的正則表達式使用「G」標誌,你可以使用exec 方法多次找到相同的字符串匹配連續。 當你這樣做時,搜索在海峽指定的字符串開始由 正則表達式的lastIndex屬性

所以,當你的正則表達式有公司標誌,並使用exec方法一次,下一次執行它它會在第一場比賽後搜索比賽。在這種情況下,沒有:exec將返回null,lastIndex屬性將被重置。

例如:

var str = "abcdef"; 
//  ^starting index for search is here 
var regex = /ab/g; 

regex.exec(str); 
// str: "abcdef" 
//  ^starting index for search is now here 

regex.exec(str); 
// no match found from starting index, return null and reset 
// str: "abcdef" 
//  ^starting index reset 

我對我不好的字眼等等對不起,我不是完全清醒......

0

你可能想從你的正則表達式中刪除g標誌,根據你想達到什麼目的。而且,那些空的捕獲組看起來沒有必要。

編輯:看起來像Reanimation擊敗了我;)