在C#中检查字符串中的字母数字字符 [英] check alphanumeric characters in string in c#
本文介绍了在C#中检查字符串中的字母数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用了以下代码,但它返回false,尽管它应该返回true
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;
}
推荐答案
尝试以下方法:
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.
在上面的示例中:
- ^-表示字符串的开头
- [] *-方括号之间可以包含任意数量的字符
- a-zA-Z0-9-任何字母数字字符
- \ s-任何空格字符(空格/制表符等)
- ,-逗号
- $-字符串的结尾
这篇关于在C#中检查字符串中的字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文