Regex in C# to Handle case-insensitive

Introduction

In C#, you can use the System.Text.RegularExpressions namespace to work with regular expressions. From this blog, you can handle the case insensitive with regex.

To handle case-insensitive

Basically, we use the below regular expression to validate and restrict gmail.com from the email address entered by the user.

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.

Conclusion

We have seen a pretty handful of ways to handle the case-insensitive option with regex in C#.