开发者

In a RegEx with multiple subexpressions (i.e. using parenthesis), how do I know which one it matched?

开发者 https://www.devze.com 2023-03-22 22:27 出处:网络
So, for example: //The string to search through var str = \"This is a string /* with some //stuff in here\";

So, for example:

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

How do i know I matched the "(//)" instead of the "(here)" without running another regex against the returned match?


You can check which group is defined:

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

Running at http://jsfiddle.net/zLD5V/

0

精彩评论

暂无评论...
验证码 换一张
取 消