Home > Software design >  Verifying that a string contains only uppercase letters and numbers in C#
Verifying that a string contains only uppercase letters and numbers in C#

Time:05-05

I would use Char.IsLetterOrDigit but I need the letters to be uppercase only.

I can't seem to find a way to combine Char.IsLetterOrDigit and Char.IsUpper because digits won't be allowed when I try this way:

if (input.All(Char.IsLetterOrDigit) && input.All(Char.IsUpper))

Am I missing something here?

How can I check each letter separately?

CodePudding user response:

All() takes a predicate which can be a lambda expression. You can use this to check IsLetter && IsUpper separately from IsDigit.

input.All(c => (Char.IsLetter(c) && Char.IsUpper(c)) || Char.IsDigit(c))

Try it online

Alternatively, you could use a regular expression that matches zero or more uppercase characters or digits:

using System.Text.RegularExpressions;

Regex r = new Regex(@"^[A-Z0-9]*$");
r.IsMatch(input);

Try it online

Regex explanation:

^[A-Z0-9]*$
^               Start of string
 [A-Z0-9]       The uppercase letter characters or the digit characters
         *      Zero or more of the previous
          $     End of string

CodePudding user response:

Regex is suitable for this kind of string assertions.

Working example:

using System;
using System.Text.RegularExpressions;  
            
public class Program
{
    public static void Main()
    {
        String input = "THIS0IS0VALID";
        String pattern = "^[A-Z0-9] $";
        bool isValid = Regex.Match(input, pattern).Success;
        if(isValid) {
            Console.WriteLine("logic here...");
        } 
    }
}


Pattern breakdown (^[A-Z0-9] $):

  • ^: asserts position at start of a line
  • [A-Z0-9]: the character to be matched has to be either a capital letter or a number
  • : we can allow for one or more characters to be sequenced
  • $: asserts position at end of a line
  • Related