我有一个正则表达式:
/(alpha)|(beta)|(gamma)/gi
一些文字来匹配:
Betamax. Digamma. Alphabet. Hebetation.
该场比赛是:
beta, gamma, alpha, beta
我期待的值应该是:
1,2,0,1
......我能确定的是,在正则表达式匹配组的指数?
我有一个正则表达式:
/(alpha)|(beta)|(gamma)/gi
一些文字来匹配:
Betamax. Digamma. Alphabet. Hebetation.
该场比赛是:
beta, gamma, alpha, beta
我期待的值应该是:
1,2,0,1
......我能确定的是,在正则表达式匹配组的指数?
要访问组 ,你将需要使用.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]));
从字符串数组建立你的正则表达式,然后查找的indexOf比赛。
If we consider the exact sample you provided, the below will work:
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);
I leave it to you to make the content of the loop more dynamic / generic :p