You can use the System in C#.To work with regular expressions, use the Text.RegularExpressions namespace. You may handle case insensitive regex from this blog. To deal with case-insensitive situations
Essentially, we use the regular expression below to validate and restrict gmail.com from the user's email address.string pattern = "^[a-zA-Z0-9._%+-]+@(?!gmail\.com)([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$";
The problem with the above pattern is it is case-insensitive. When the user type [email protected], it will fail. We used to convert the email address to lowercase before the pattern check, but we can handle it with the regex itself using the below options.
1. Using RegexOptions.IgnoreCase
string pattern = "^[a-zA-Z0-9._%+-]+@(?!gmail\\.com)([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}$";
string input = "[email protected]";
Regex regex = new Regex(pattern,RegexOptions.IgnoreCase);
bool isValid = regex.IsMatch(input);
We can use the IgnoreCase flag when creating a Regex object.
2. Using (?i) Modifier
string pattern = @"(?i)^[a-zA-Z0-9._%+-]+@(?!gmail\\.com)([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}$";
string input = "[email protected]";
Regex regex = new Regex(pattern);
bool isValid = regex.IsMatch(input);
Modifier (?i) turns on the case insensitive mode for the rest of the pattern.
We have seen a pretty handful of ways to handle the case-insensitive option with regex in C#.
0 comments:
Post a Comment