所以,例如:
//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)”而没有针对返回的匹配运行另一个正则表达式?
答案 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]);
}
运行