I want to write a conditional regex which matches 1 of 2 patterns.
To do that, I have a simple conditional:
/((pattern1)|(pattern2))/gi
Problem is, within pattern1, I may have multiple capture groups — lets say 3 of them, but within pattern2, I have 5 of them.
How can I tell WHICH of the 2 patterns matched? I need to be able to request the proper capture groups (by number) for my output.
I guess in my example you could just check for the existence of any capture group value above 3, but say I had an equal amount of capture groups in each pattern. I’m thinking there must be a good way to do this — I’m using PHP or JavaScript. Let me know if more details are needed.
Thanks in advance!
The patterns are numbered based on the regex itself, not on the outcome of an actual match. In your example, the overall group will always be group 1, then the first possibility (“pattern1”) will be group 2, and the other will be group 3. If “pattern2” matches, then group 3 will be non-empty and group 2 will be empty, in other words. Group 1 will always be the same as the non-empty one of groups 2 and 3.