在具有多个子表达式的RegEx中(即使用括号),我如何知道它匹配哪一个?

时间:2011-07-26 23:19:16

标签: regex

所以,例如:

//The string to search through
var str = "This is a string /* with some //stuff in here";

//I'm matching three possible things: "here" or "//" or "/*"
var regEx = new RegExp( "(here)|(\\/\\/)|(\\/\\*)", "g" );

//Loop and find them all
while ( match = regEx.exec( str ) )
{
    //Which one is matched? The first parenthesis subexpression? The second?
    alert( match[ 0 ] );
}

我怎么知道我匹配“(//)”而不是“(here)”而没有针对返回的匹配运行另一个正则表达式?

1 个答案:

答案 0 :(得分:1)

您可以检查定义了哪个组:

var str = "This is a string /* with some //stuff in here";    
var regEx = /(here)|(\/\/)|(\/\*)/g;

while(match = regEx.exec(str)){
    var i;
    for(i = 1; i < 3; i++){
        if(match[i] !== undefined)
            break;
    }

    alert("matched group " + i + ": " + match[i]);
}

http://jsfiddle.net/zLD5V/

运行