Get the index of the group that matched in a regexp?

喜欢而已 提交于 2019-12-04 16:17:06
Bergi

To access the groups, you will need to use .exec() repeatedly:

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]));

If you want the indizes zero-based, you could use

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

Build your regex from an array of strings, and then lookup the matches with 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!