C# Regex to allow only alpha numeric

后端 未结 6 391
野的像风
野的像风 2020-12-15 03:45

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\"

相关标签:
6条回答
  • 2020-12-15 04:31

    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.

    0 讨论(0)
  • 2020-12-15 04:33

    Sounds like you want:

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

    EXPLANATION

    ^ asserts position at the start of a line

    Match a single character present in the list below [a-zA-Z]

    » a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)

    » A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)

    Match a single character present in the list below [a-zA-Z0-9]*

    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

    a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)

    A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)

    0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)

    $ asserts position at the end of a line

    Demo

    0 讨论(0)
  • 2020-12-15 04:34
    ^[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]*$
    
    0 讨论(0)
  • 2020-12-15 04:39

    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
      }
      
    0 讨论(0)
  • 2020-12-15 04:42

    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)

    0 讨论(0)
  • 2020-12-15 04:45

    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);
        }
    
    0 讨论(0)
提交回复
热议问题