A regular expression that checks the number of characters

I need to write a .NET Regular Expression that checks if a string is alpha-numeric and has 4 or 8 characters (no less and no more). How can i do this? I tried ([a-zA-Z0-9] {4}) | ([a-zA-Z0-9] {8}), but it does not work.

+4
source share
2 answers

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}$ 
+5
source

You should try using word boundaries or the beginning / end of a line. For example, you want to create a string that is alphanumeric 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 by using \ w as the word character

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

Since you are in .NET, remember to avoid backslashes when creating a regular expression pattern (if enclosed in quotation marks).

In addition, you do not need parentheses around each 4 or 8 character (but you need it around the change), because the change channel (vertical panel) has the lowest priority.

+1
source

All Articles