You need to include the beginning and end of string bindings, otherwise it may correspond to part of the string:
^([a-zA-Z0-9]{4}|[a-zA-Z0-9]{8})$
Here is a quick example of using this regular expression:
Regex regex = new Regex("^([a-zA-Z0-9]{4}|[a-zA-Z0-9]{8})$"); string[] tests = { "abcd", "0123", "01234567", "012345", "0123456789" }; foreach (string test in tests) { Console.WriteLine("{0}: {1}", test.PadRight(10), regex.IsMatch(test)); }
Result:
abcd: True
0123: True
01234567: True
012345: False
0123456789: False
An alternative way to write a regular expression is as follows:
^(?:[a-zA-Z0-9]{4}){1,2}$
source share