tags:

views:

47

answers:

2

I have to write a .NET Regular Expression which validates if a string is alpha-numeric and has 4 or 8 characters (nothing less, nothing more). How can I do that? I tried with ([a-zA-Z0-9]{4})|([a-zA-Z0-9]{8}) but it doesn't work.

+4  A: 

You need to include start and end of line anchors otherwise it can match part of the string:

^([a-zA-Z0-9]{4}|[a-zA-Z0-9]{8})$

Here's a quick example of how to use 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 the regular expression is as follows:

^(?:[a-zA-Z0-9]{4}){1,2}$
Mark Byers
@Mark - just curious, which language is this?
ysap
@ysap: It is C#.
Mark Byers
+1  A: 

You should try a word boundary or beginning/end of line features. For example, you want to make a string that is alpha numeric with 4 or 8 characters and has no extra space:

\b([a-zA-Z0-9]{4}|[a-zA-Z0-9]{8})\b   or the string is the entire line
^([a-zA-Z0-9]{4}|[a-zA-Z0-9]{8})$

You can shorten this using \w as a word character

\b(\w{4}|\w{8})\b
^(\w{4}|\w{8})$

Since you're in .NET, don't forget to escape the backslashes when building the regex pattern (if it's enclosed in quotes).

Also, you do not need parentheses around each 4 or 8 character (but you do need it around the alteration) because the alteration pipe (vertical bar) has the lowest precedence.

Kizaru