3 ms·
A shorthand memory hook to remember "Tarzan"|(Tarzan) is that this is similar to conditional evaluation of boolean expressions. For example, in Python you often
by wildmanx 5y ago
A shorthand memory hook to remember "Tarzan"|(Tarzan) is that this is similar to conditional evaluation of boolean expressions. For example, in Python you often do
foo = foo or [ 23, 42 ]
Or more generally:
foo = foo or ConstructSomeFoo()
If foo is None then it gets this default value or the newly constructed object, otherwise it's unchanged. Key here is that what's after "or" is not even evaluated if the first operand is already evaluating to True.
So, the left "Tarzan" eats up the matching substring that we do not want, while the right (Tarzan) matches what we do want, but only if the left one didn't already hit.
- ganafagol 5y agoNeedless to say, all of this only works if the regex engine satisfies certain assumptions, i.e., order of "evaluation" is guaranteed. In abstract semantics of regular expressions, a|b and b|a are equivalent.
- BeeOnRope 5y agoIt doesn't rely on order of operations, at least in this example? "Tarzan" will match one character earlier than Tarzan as the sting is scanned, so it would be discarded even if you flipped the order of the alternation. This isn't true of examples where the good and bad marches can start at the same character.
- ganafagol 5y agoThat the input is matched position by position to alternative patterns and the first one is returned is another one of said assumptions.