我使用了以下代码但它返回false虽然它应该返回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;
}
Run Code Online (Sandbox Code Playgroud)
cho*_*dze 50
试试这个:
public static Boolean isAlphaNumeric(string strToCheck)
{
Regex rg = new Regex(@"^[a-zA-Z0-9\s,]*$");
return rg.IsMatch(strToCheck);
}
Run Code Online (Sandbox Code Playgroud)
如果你在正则表达式中指定,你的字符串应该包含什么,而不是它必须包含的内容,那就更难以理解了.
在上面的例子中:
Yai*_*evi 32
public static bool IsAlphaNumeric(string strToCheck)
{
return strToCheck.All(char.IsLetterOrDigit);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
我需要一种方法来查看字符串是否包含任何字母数字,而不使用正则表达式...
public static bool ContainsAlphaNumeric(string strToCheck)
{
foreach(char c in strToCheck)
{
if (char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
10001 New York, NY 包含逗号和空格 - 不包括字母数字
您需要调整表达式以允许逗号和空格.
此外,您可能希望重命名该函数,以便其他开发人员清楚它更像是一个验证器而不是isAlphaNumeric()函数.
如果您想要非正则表达式 ASCIIA-z 0-9检查,则不能使用char.IsLetterOrDigit(),因为它包含其他 Unicode 字符,并且对于 unicode 标量值不可靠/不稳定。
您可以做的是检查字符代码范围。
下面的内容有点冗长,但这是为了便于理解,而不是为了代码高尔夫。
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;
}
Run Code Online (Sandbox Code Playgroud)