Why order matters in this RegEx with alternation?

The order matters since that is the order which the Regex engine will try to match.

Case 1: Number of rooms|[0-9]*

In this case the regex engine will first try to match the text “Number of room”. If this fails will then try to match numbers or nothing.

Case 2: [0-9]*|Number of rooms:

In this case the engine will first try to match number or nothing. But nothing will always match. In this case it never needs to try “Number of rooms”

This is kind of like the || operator in C#. Once the left side matches the right side is ignored.

Update:
To answer your second question. It behaves differently with the RegularExpressionValidator because that is doing more than just checking for a match.

// .....
Match m = Regex.Match(controlValue, ValidationExpression);
return(m.Success && m.Index == 0 && m.Length == controlValue.Length); 
// .....

It is checking for a match as well as making sure the length of the match is the whole string. This rules out partial or empty matches.

Leave a Comment