Given this code:
const regex = /graph|photograph/;
'A photograph'.match(regex);
// Output: [ 'photograph', index: 2, input: 'A photograph', groups: undefined ]
Why is the engine not finding graph
first? After looking at similar SO questions and the ECMAScript docs, I can see that
The
|
regular expression operator separates two alternatives. The pattern first tries to match the left Alternative (followed by the sequel of the regular expression); if it fails, it tries to match the right Disjunction (followed by the sequel of the regular expression).
Now, the above quote covers the case /photo|photograph/
where the alternatives share a common beginning, but the case where they share a common ending appears to be governed by a different rule.
I am content with the result I am getting, as in my use case I prefer to get the longest match, not the earliest one, but I would like to know why this happens, so I can be sure this isn't just a coincidence that is bound to change in the future.