简体   繁体   中英

C# Regex to allow only alpha numeric

I have the following regex ^[a-zA-Z0-9]+$ which would allow alpha numeric characters. The problem here is that if I enter only numeric character like "897687", then the regex still matches. I don't want that to happen. There should be at least one text character and it should start with a text character. For example like "a343" or "a98bder" or "a4544fgf343"

It would be great if you could help me to improve my regex for this.

听起来像你想要的:

^[a-zA-Z][a-zA-Z0-9]*$

Just in case that the ASCII characters are at some point not enough, here the Unicode version:

^\p{L}[\p{L}\p{N}]*$

\\p{L} is any Unicode code point that has the property letter ==> Any letter from any language (that is in Unicode)

\\p{N} is any Unicode code point that has the property number ==> Any number character from any language (that is in Unicode)

^[a-zA-Z][a-zA-Z0-9]*$

Should do the trick!

Alternatively, if you wish to include all alphanumeric plus an underscore you can use:

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

This function will return true or false based on whether the Regular Expression is matched or not,

   public static Boolean isAlphaNumeric(string strToCheck)
    {
        Regex rg = new Regex(@"^[a-zA-Z0-9\s,]*$");
        return rg.IsMatch(strToCheck);
    }

Or slightly less verbose than the accepted answer:

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

C# regex has character class indicator "\\w" for alphanumeric characters, but does not have a character class for just alphabetic (no digits), hence you have to specify class set [a-zA-Z] manually.

This is the best solution to check alphanumeric,

  • if it is only string - "Error".
  • if it is only integer - "Error".
  • if it is alphanumeric -"Success".

     if (System.Text.RegularExpressions.Regex.IsMatch(txt.Text, @"[a-zA-Z]") && System.Text.RegularExpressions.Regex.IsMatch(txt.Text, @"[0-9]") { // Success - It is alphanumric } else { // Error - It is not alphanumric } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM