Handling case-insensitive regex in C#

Leave a Comment

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#.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
Next PostNewer Post Previous PostOlder Post Home


Post a Comment