Alternation meta character (|) can be used to match a single regular expression out of several possible regular expressions. Since regex engine is eager to find the match. It stops searching as soon as it finds a valid match. The consequence is that in certain situations, the order of the alternatives matters.

Consider below string and regular exression

String : SetValue
RegEx : Get|GetValue|Set|SetValue


The regex engine starts at the first token in the regex, G, and at the first character in the string, S. The match fails. So it continues with the second option, being the second G in the regex. The match fails again. The next token is the first S in the regex. The match succeeds, and the engine continues with the next character in the string, as well as the next token in the regex. At this point, the third option in the alternation has been successfully matched.

Because the regex engine is eager, it considers the entire alternation to have been successfully matched as soon as one of the options has. In this example, there are no other tokens in the regex outside the alternation, so the entire regex has successfully matched Set in SetValue.


By changing the order of regular expression to GetValue|Get|SetValue|Set, SetValue is attempted before Set, and the engine matches the entire string.