How can I validate a string to only allow alphanumeric characters in it?

后端 未结 10 1215
执笔经年
执笔经年 2020-12-12 15:06

How can I validate a string using Regular Expressions to only allow alphanumeric characters in it?

(I don\'t want to allow for any spaces either).

10条回答
  •  抹茶落季
    2020-12-12 16:09

    Same answer as here.

    If you want a non-regex ASCII A-z 0-9 check, you cannot use char.IsLetterOrDigit() as that includes other Unicode characters.

    What you can do is check the character code ranges.

    • 48 -> 57 are numerics
    • 65 -> 90 are capital letters
    • 97 -> 122 are lower case letters

    The following is a bit more verbose, but it's for ease of understanding rather than for code golf.

        public static bool IsAsciiAlphaNumeric(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }
    
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] < 48) // Numeric are 48 -> 57
                {
                    return false;
                }
    
                if (str[i] > 57 && str[i] < 65) // Capitals are 65 -> 90
                {
                    return false;
                }
    
                if (str[i] > 90 && str[i] < 97) // Lowers are 97 -> 122
                {
                    return false;
                }
    
                if (str[i] > 122)
                {
                    return false;
                }
            }
    
            return true;
        }
    

提交回复
热议问题