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

后端 未结 10 1214
执笔经年
执笔经年 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;
        }
    
    0 讨论(0)
  • 2020-12-12 16:10

    In order to check if the string is both a combination of letters and digits, you can re-write @jgauffin answer as follows using .NET 4.0 and LINQ:

    if(!string.IsNullOrWhiteSpace(yourText) && 
    yourText.Any(char.IsLetter) && yourText.Any(char.IsDigit))
    {
       // do something here
    }
    
    0 讨论(0)
  • I needed to check for A-Z, a-z, 0-9; without a regex (even though the OP asks for regex).

    Blending various answers and comments here, and discussion from https://stackoverflow.com/a/9975693/292060, this tests for letter or digit, avoiding other language letters, and avoiding other numbers such as fraction characters.

    if (!String.IsNullOrEmpty(testString)
        && testString.All(c => Char.IsLetterOrDigit(c) && (c < 128)))
    {
        // Alphanumeric.
    }
    
    0 讨论(0)
  • 2020-12-12 16:13

    ^\w+$ will allow a-zA-Z0-9_

    Use ^[a-zA-Z0-9]+$ to disallow underscore.

    Note that both of these require the string not to be empty. Using * instead of + allows empty strings.

    0 讨论(0)
提交回复
热议问题