windows C# - 在 if 语句中使用正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6415620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# - Using regex with if statements
提问by Dan
I have some code that checks a fields input against a regex, although for some reason (no matter what I put in the field, it returns flase. Is there something I have missed?
我有一些代码可以根据正则表达式检查字段输入,但出于某种原因(无论我在字段中输入什么,它都会返回 flase。有什么我遗漏的吗?
private void textBox5_Validating(object sender, CancelEventArgs e)
{
String AllowedChars = @"^a-zA-Z0-9.$";
if (Regex.IsMatch(textBox5.Text, AllowedChars))
{
MessageBox.Show("Valid");
}
else
{
MessageBox.Show("Invalid");
}
}
回答by naivists
The regex makes no sense to me. This one would (notice the square brackets used for defining an alphabet):
正则表达式对我来说毫无意义。这将(注意用于定义字母表的方括号):
String AllowedChars = @"^[a-zA-Z0-9]*$";
回答by Ed Chapel
What you want is to group those characters and allow 0 or more:
您想要的是将这些字符分组并允许 0 个或多个:
@"^[a-zA-Z0-9.]*$"
Otherwise, what you posted allows "a-zA-Z0-9" and one more character only.
否则,你可以发布“A-ZA-Z0-9”和一个或多个字符只。
回答by Jon
Probably incorrect regex. Maybe you meant this:
可能不正确的正则表达式。也许你的意思是:
String AllowedChars = @"^[a-zA-Z0-9]*$";
This would allow any number (including none) of alphanumeric chars. I have removed the period (which matches any character) because it does not make much sense in this context.
这将允许任意数量(包括无)的字母数字字符。我删除了句点(它匹配任何字符),因为它在这种情况下没有多大意义。