Home > OS >  Regex to Allow 1st letter of a string only Alphabet in C#
Regex to Allow 1st letter of a string only Alphabet in C#

Time:06-13

I have a case where i need to allow Alphanumeric but 1st letter of the string should always be Alphabet only

Below is sample case

string text1 = "A1222"; Valid
string text2 = "1A22"; // Invalid

CodePudding user response:

A variant of what was already said in the comments would be

Regex reg = new Regex(@"^[a-z][a-z\d]*$", RegexOptions.IgnoreCase);

That one is not particularly complex, but for complex ones it is very nice making them case insensitive.

Warning: Do note that [A-z] would yield wrong results as mentioned in this related question Difference between regex [A-z] and [a-zA-Z]

CodePudding user response:

You can use this

^[a-zA-Z][a-zA-Z\d]*$

where

  1. "[a-zA-Z]" matches a character in the ranges a to z and A to Z
  2. "\d" matches any digit character
  3. "*" matches 0 or more of the previous pattern
  •  Tags:  
  • c#
  • Related