How match n+ instance of something inside a subexpression without increasing subexpression count?
(I know my question's confusing, so see below for example/explanation)
I am trying to match a bunch of things in one big regex and then figure out which subexpression I matched. The problem is when one of my subexpressions has a "collection/sequence" in it, that throws off the index of the subexpressions.
For example, in the below expression, the check for "foo" would be at index 3:
/(one)|(two)|(foo)/g
But in this one, it's at index 4 (and yes this is a dumb regex, but the example fits):
/(one)|(([tT][wW])?o)|(foo)/g
If you used the below code to try and find "foo", you'd get something 开发者_运维问答like:
var str = "Some string that only matches foo";
while ( match = reg.exec( str ) )
{
for ( var i = 1; i < match.length; i++ )
{
//Should be 3 but it's not
if( match[ i ] !== undefined ) break;
}
//This won't match foo, because it's now the wrong index
alert( match[ i ] );
}
How can I do a "one or more" type expression inside a subexpression parentheses without affecting the indexes returned to "match" via "regex.exec"?
(NOTE: don't hesitate to tell me if this is in any way unclear and I'll try to come up with a better example and full example code)
(pattern)
matches and captures the match. If you want to match, but not capture, use (?:pattern)
that's because foo will always be at index 4 with your above regex because the foo
group is the fourth captured group in your expression. You can use ?:
to indicate that a group should not capture like:
/(one)|((?:[tT][wW])?o)|(foo)/g
Now foo will be back in index 3.
精彩评论