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

后端 未结 10 1213
执笔经年
执笔经年 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 15:48

    You could do it easily with an extension function rather than a regex ...

    public static bool IsAlphaNum(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return false;
    
        for (int i = 0; i < str.Length; i++)
        {
            if (!(char.IsLetter(str[i])) && (!(char.IsNumber(str[i]))))
                return false;
        }
    
        return true;
    }
    

    Per comment :) ...

    public static bool IsAlphaNum(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return false;
    
        return (str.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c)));
    }
    
    0 讨论(0)
  • 2020-12-12 15:49

    I advise to not depend on ready made and built in code in .NET framework , try to bring up new solution ..this is what i do..

    public  bool isAlphaNumeric(string N)
    {
        bool YesNumeric = false;
        bool YesAlpha = false;
        bool BothStatus = false;
    
    
        for (int i = 0; i < N.Length; i++)
        {
            if (char.IsLetter(N[i]) )
                YesAlpha=true;
    
            if (char.IsNumber(N[i]))
                YesNumeric = true;
        }
    
        if (YesAlpha==true && YesNumeric==true)
        {
            BothStatus = true;
        }
        else
        {
            BothStatus = false;
        }
        return BothStatus;
    }
    
    0 讨论(0)
  • 2020-12-12 15:51

    In .NET 4.0 you can use LINQ:

    if (yourText.All(char.IsLetterOrDigit))
    {
        //just letters and digits.
    }
    

    yourText.All will stop execute and return false the first time char.IsLetterOrDigit reports false since the contract of All cannot be fulfilled then.

    Note! this answer do not strictly check alphanumerics (which typically is A-Z, a-z and 0-9). This answer allows local characters like åäö.

    Update 2018-01-29

    The syntax above only works when you use a single method that has a single argument of the correct type (in this case char).

    To use multiple conditions, you need to write like this:

    if (yourText.All(x => char.IsLetterOrDigit(x) || char.IsWhiteSpace(x)))
    {
    }
    
    0 讨论(0)
  • 2020-12-12 15:53

    Use the following expression:

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

    ie:

    using System.Text.RegularExpressions;
    
    Regex r = new Regex("^[a-zA-Z0-9]*$");
    if (r.IsMatch(SomeString)) {
      ...
    }
    
    0 讨论(0)
  • 2020-12-12 16:00

    While I think the regex-based solution is probably the way I'd go, I'd be tempted to encapsulate this in a type.

    public class AlphaNumericString
    {
        public AlphaNumericString(string s)
        {
            Regex r = new Regex("^[a-zA-Z0-9]*$");
            if (r.IsMatch(s))
            {
                value = s;                
            }
            else
            {
                throw new ArgumentException("Only alphanumeric characters may be used");
            }
        }
    
        private string value;
        static public implicit operator string(AlphaNumericString s)
        {
            return s.value;
        }
    }
    

    Now, when you need a validated string, you can have the method signature require an AlphaNumericString, and know that if you get one, it is valid (apart from nulls). If someone attempts to pass in a non-validated string, it will generate a compiler error.

    You can get fancier and implement all of the equality operators, or an explicit cast to AlphaNumericString from plain ol' string, if you care.

    0 讨论(0)
  • 2020-12-12 16:08

    Based on cletus's answer you may create new extension.

    public static class StringExtensions
    {        
        public static bool IsAlphaNumeric(this string str)
        {
            if (string.IsNullOrEmpty(str))
                return false;
    
            Regex r = new Regex("^[a-zA-Z0-9]*$");
            return r.IsMatch(str);
        }
    }
    
    0 讨论(0)
提交回复
热议问题