C# - Using regex with if statements
10,715
Solution 1
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]*$";
Solution 2
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.
Solution 3
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.
Author by
Dan
Updated on July 10, 2022Comments
-
Dan almost 2 years
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 AllowedChars = @"^a-zA-Z0-9.$"; if (Regex.IsMatch(textBox5.Text, AllowedChars)) { MessageBox.Show("Valid"); } else { MessageBox.Show("Invalid"); } }
-
Tadmas almost 13 yearsThe period may have been intended to be a literal period character rather than a metacharacter (perhaps "www.example.com" is a valid input), especially considering the variable name of
AllowedChars
. In that case, it should be included within the square brackets.