29

I have used the following code but it is returning false though it should return true

string check,zipcode;
zipcode="10001 New York, NY";
check=isalphanumeric(zipcode)

public static Boolean isAlphaNumeric(string strToCheck)
{
    Regex rg = new Regex("[^a-zA-Z0-9]");

    //if has non AlpahNumeric char, return false, else return true.
    return rg.IsMatch(strToCheck) == true ? false : true;
}
FortyTwo
  • 2,414
  • 3
  • 22
  • 33
iProgrammer
  • 3,099
  • 3
  • 33
  • 59
  • 1
    You need to loosen it up so it allows spaces and commas. – Marko May 31 '11 at 05:33
  • There is ',' char in yuor sample string – Stecya May 31 '11 at 05:34
  • http://stackoverflow.com/q/336210/82449 might help. – KMån May 31 '11 at 05:34
  • Please see the solution in this SO post - http://stackoverflow.com/questions/181356/regex-to-match-alphanumeric-and-spaces – Jits May 31 '11 at 05:34
  • Your code has 5 errors: 1.) The ^ excludes the following characters in the bracket. 2.) You do not allow comma and space, 3.) The ^ as the FIRST character and the $ as the LAST character are missing. 4.) You need to allow also the comma, which is not alphanumeric, so your function has the wrong name. 5.) "== true ? false : true" is complete nonsense. To invert a bool use the "not" operator "!". If the regex would be correct there would be no need to invert the result. I don't understand why people give you 10 up-votes for such a shamefull code? 10 down-votes would be more adequate. – Elmue Dec 03 '15 at 13:41

9 Answers9

64

Try this one:

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

It's more undestandable, if you specify in regex, what your string SHOULD contain, and not what it MUST NOT.

In the example above:

  • ^ - means start of the string
  • []* - could contain any number of characters between brackets
  • a-zA-Z0-9 - any alphanumeric characters
  • \s - any space characters (space/tab/etc.)
  • , - commas
  • $ - end of the string
chopikadze
  • 4,219
  • 26
  • 30
  • This is the only correct answer on this page. Please note, that this regex also permits a string that is completely empty. So I would replace the * with a +. The comma is not alphanumeric, so the name of the function is misleading. If you want a shorter version you can write: @"^[\w\s,]+$" – Elmue Dec 03 '15 at 13:32
  • 1
    I added an answer that avoids regex, and only accepts `a-z A-Z 0-0`, unlike the majority of answers using the `char` functions. It's as simple as checking for character code ranges. – Douglas Gaskell Mar 06 '20 at 19:57
  • I just ran a test, and `zipcode.Any(c => char.IsLetterOrDigit(c));` takes about 1/100 the time as the regex answer, and supports non-ascii characters. (at least with the sample zip code input. – Jamie F Dec 04 '20 at 19:59
  • @JamieF Note that `char.IsLetterOrDigit()` is not stable or reliable if there is any chance of receiving unicode input where the characters are unicode scalar values. Similarly it lets through non A-z characters from other languages. https://learn.microsoft.com/en-us/dotnet/api/system.text.rune?view=net-5.0 – Douglas Gaskell Aug 10 '21 at 20:32
43
    public static bool IsAlphaNumeric(string strToCheck)
    {
        return strToCheck.All(char.IsLetterOrDigit);
    }
Yair Levi
  • 1,261
  • 10
  • 11
  • 2
    @Elmue I still find this answer more general and more useful. I was not searching for a solution that gave me letters, digits, and a few one-off punctuation characters. I googled for a solution for letters and digits, and this answer serves me best. – Millie Smith Feb 05 '17 at 22:14
  • I did not say that this answer is wrong. My comment refers to the comment of John Saunders above. – Elmue Feb 06 '17 at 14:51
  • My mistake @Elmue – Millie Smith Feb 16 '17 at 00:25
6

I needed a method to see if the string contains any Alpha Numeric, without using Regex...

  public static bool ContainsAlphaNumeric(string strToCheck)
        {
            foreach(char c in strToCheck)
            {
                if (char.IsLetterOrDigit(c))
                {
                    return true;
                }
            }
            return false;
        }
Deepak Saini
  • 2,810
  • 1
  • 19
  • 26
James Heacock
  • 61
  • 1
  • 1
6

10001 New York, NY contains a comma and spaces -- not alphanumeric

You need to adjust your expression to allow commas and spaces.

Also, you will probably want to rename the function so that it is clear to other developers that it is more of a validator than an isAlphaNumeric() function.

Brian Webster
  • 30,033
  • 48
  • 152
  • 225
5

If you want a non-regex ASCII A-z 0-9 check, you cannot use char.IsLetterOrDigit() as that includes other Unicode characters, and is unreliable/unstable with unicode scalar values.

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;
    }
Douglas Gaskell
  • 9,017
  • 9
  • 71
  • 128
  • +1 for this. I like the regex solution, but if it has an issue, at least 80% of the devs actually working in the real world will spend significant time troubleshooting that wouldn't be necessary with this one. Not saying it's a bad solution, just that yours is also excellent depending on the needs/approach of the dev team – EGP Mar 10 '23 at 13:10
2

When the ^ is in the [ ] it means everything but these characters.

rerun
  • 25,014
  • 6
  • 48
  • 78
0
tring check,zipcode;
zipcode="10001 New York, NY";
check=isalphanumeric(zipcode)

    public static Boolean isAlphaNumeric(string strToCheck)
            {
                Regex rg = new Regex("[^a-zA-Z0-9]");

                //if has non AlpahNumeric char, return false, else return true.
                return rg.IsMatch(strToCheck) == true ? false : true;
            }

this code return always false, because the symbole ^ means that's this string doesn't contains any alphanumeric caractere, you need to delete the this ^

hedi
  • 1
  • Your answer is wrong. The ^ is not the only error. Even after deleting it, it will still be wrong. There are multiple errors in this regex. Do you think you will earn reputation with answers like these? – Elmue Dec 03 '15 at 13:03
0

Back in my perl days, I would have used this regular expression:

\w+

which means one or more word character. A word character is basically a-zA-Z0-9 and basically does not care about punctuation or spaces. So if you just want to make sure that there is someting of value in the string, this is what I have used in C#:

public static Boolean isAlphaNumeric(string strToCheck)
{
    Regex rg = new Regex(@"\w+");
    return rg.IsMatch(strToCheck);
}

Thanks to Chopikadze for the basic structure.

I do think that this one would be faster since instead of checking through the entire string, it would stop at the first instance of a word character and return a true.

  • This answer is also wrong. Your regex does not permit spaces and it only SEARCHES for any word INSIDE the given string. It does NOT check that the ENTIRE string IS alphanumeric. So your answer has multiple errors! – Elmue Dec 03 '15 at 13:09
0

Char static methods can be used too

bool IsAlphaNumeric(char charToCheck) => char.IsLetter(charToCheck) || char.IsDigit(charToCheck);
zzfima
  • 1,528
  • 1
  • 14
  • 21