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=isalpha
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 ^
public static bool IsAlphaNumeric(string strToCheck)
{
return strToCheck.All(char.IsLetterOrDigit);
}
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.
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:
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;
}
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.
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;
}