我编写了以下正则表达式,仅匹配那些没有空格且没有特殊字符的单词。但它也与包含空间的单词匹配。有什么问题?
Regex rgx = new Regex("[a-zA-Z0-9]+");
if (!rgx.IsMatch(TextBox_EntityType.Text))
{
}
答案 0 :(得分:2)
您可以更改支票的逻辑,使其反之亦然,并采取相应的措施:
Regex rgx = new Regex("[^a-zA-Z0-9]");
# Match if there is something that is not alphanumeric
if (rgx.IsMatch(TextBox_EntityType.Text))
{
# Do what should be done if the text contains non-alphanumeric
}
这一个也可以正常工作,因为.IsMatch()
在字符串中的任何地方查找匹配项(它会尽力找到匹配项),所以要么让它与Nikhil建议的锚点匹配整个字符串,要么像我一样颠倒逻辑(我认为应该稍微提高效率,但不是基准)。
答案 1 :(得分:1)
应为^[a-zA-Z0-9]+$
添加^和$。
^
匹配字符串的开头,$
匹配结尾。