开发者

C# - Using regex with if statements

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?

private void textBox5_Validating(object sender, CancelEventArgs e)
{
    String Allowe开发者_Go百科dChars = @"^a-zA-Z0-9.$";
    if (Regex.IsMatch(textBox5.Text, AllowedChars))
    {
        MessageBox.Show("Valid");
    }
    else
    {
        MessageBox.Show("Invalid");
    }
}


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]*$";


What you want is to group those characters and allow 0 or more:

@"^[a-zA-Z0-9.]*$"

Otherwise, what you posted allows "a-zA-Z0-9" and one more character only.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜