Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining which subpattern was matched when using '|' operator in regex

I have a regular expression that is pieced together with a '|', aka OR operator, which is comprised of smaller sub-patterns. I'm trying to determine which sub-pattern was matched, but the RegExp engine will only give me the entire expression.

Examples:

Here is my compiled (approximate), pieced expression (massively simplified for comprehension:

/^somestring-(\w+)$|^notherstring-(\d+)-(\w+)$|^laststring-(\w+)-([a-f])$/g

Here is the input text:

laststring-eof

So in my matches array, I see a few indexes with "undefined values" (since there are a couple of attempted matches before that don't match the entire expression), but also I get my match "eof".

This is all great, gives me most of what I want. What I'm NOT getting that I need, is to know that the sub-pattern that was matched was "^laststring-(\w+)$", or at the least, to know that is was the third sub-pattern in the main expression. I can't rely on the length of the match array, since each sub-pattern can have an indefinite number of match groups.

I tried regexp.lastIndex, but that property only gives me the last match within the sub-pattern, not the offset of the sub-pattern within the entire expression.

like image 246
rpaskett Avatar asked Mar 01 '26 18:03

rpaskett


1 Answers

I'm not sure if this would work, but I think if you put () brackets around each of the subgroups you should be able to check which of them is non-null if the expression matches, and in that way you can see which pattern matches.

In your case that would create 3 additional sub-groups, and if I count correctly it would be something like this:

first group = first sub-pattern

second group = first matching group in first sub-pattern

third group = second sub-pattern

fourth group and fifth group = the sub-patterns in the second sub-pattern

sixth = third sub-group

So you check the first, third and sixth matching group for which one is non-null and that's your matching pattern.

like image 88
Andreas Müller Avatar answered Mar 03 '26 08:03

Andreas Müller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!