30

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; } 
5
  • 1
    You need to loosen it up so it allows spaces and commas. Commented May 31, 2011 at 5:33
  • There is ',' char in yuor sample string Commented May 31, 2011 at 5:34
  • stackoverflow.com/q/336210/82449 might help. Commented May 31, 2011 at 5:34
  • Please see the solution in this SO post - stackoverflow.com/questions/181356/… Commented May 31, 2011 at 5: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. Commented Dec 3, 2015 at 13:41

9 Answers 9

65

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
Sign up to request clarification or add additional context in comments.

4 Comments

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,]+$"
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.
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.
@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. learn.microsoft.com/en-us/dotnet/api/…
47
 public static bool IsAlphaNumeric(string strToCheck) { return strToCheck.All(char.IsLetterOrDigit); } 

3 Comments

@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.
I did not say that this answer is wrong. My comment refers to the comment of John Saunders above.
My mistake @Elmue
7

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; } 

1 Comment

+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
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.

Comments

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; } 

1 Comment

This allows non A-Z letters such as Chinese characters...etc
2

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

Comments

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 ^

1 Comment

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?
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.

1 Comment

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!
0

Char static methods can be used too

bool IsAlphaNumeric(char charToCheck) => char.IsLetter(charToCheck) || char.IsDigit(charToCheck); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.