2013-02-16 59 views

回答

5

access the groups,你將需要使用.exec()反覆:

var regex = /(alpha)|(beta)|(gamma)/gi, 
    str = "Betamax. Digamma. Alphabet. Hebetation."; 
for (var nums = [], match; match = regex.exec(str);) 
    nums.push(match.lastIndexOf(match[0])); 

如果你想indizes從零開始,你可以使用

nums.push(match.slice(1).indexOf(match[0])); 
+0

這是我最喜歡的,我喜歡你使用結果的操縱來獲得零基結果。 – 2013-02-16 16:46:06

+1

是的,它看起來不錯,並允許我們使用'indexOf'而不是後向搜索。雖然,只是將「 - 1」附加到第一個將會更短,更高效:) – Bergi 2013-02-16 16:48:49

1

從一個字符串數組中構建正則表達式,然後用indexOf查找匹配項。

1

如果我們考慮您所提供的確切的樣品,下面將工作:

var r = /(alpha)|(beta)|(gamma)/gi; 
var s = "Betamax. Digammas. Alphabet. Habetation."; 

var matched_indexes = []; 
var cur_match = null; 

while (cur_match = r.exec(s)) 
{ 
    matched_indexes.push(cur_match[1] ? 0 : cur_match[2] ? 1 : 2); 
} 

console.log(matched_indexes); 

我把它交給你,使循環更加動態/通用的內容:對

相關問題