C# RegexOptions.IgnoreCase for Case-Insensitive Regex

Regex type

Sometimes text data has inconsistent casing. Some data is uppercase, and some lowercase, but both are valid. The Regex type in the C# language by default is case-sensitive. However, you can apply the RegexOptions.IgnoreCase enumerated constant to relax this.

This C# program uses the Regex.IsMatch method with RegexOptions.IgnoreCase.

Example

Note

As we begin, remember that the RegexOptions type is an enum type; it is typically passed as the last argument to a Regex method, such as IsMatch or Split. This example demonstrates how the RegexOptions.IgnoreCase enumerated constant affects the result of the IsMatch method on an input that is in a different case.

When IgnoreCase is specified, the match succeeds; otherwise, it fails. IgnoreCase will relax the regular expression, making more data match than would otherwise.

Program that uses RegexOptions.IgnoreCase constant [C#]

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
	// The input string has an uppercase trailing letter.
	const string value = "carroT";

	// Print result of IsMatch method:
	// ... With IgnoreCase;
	// ... And without any options set.
	Console.WriteLine(Regex.IsMatch(value, "carrot", RegexOptions.IgnoreCase));
	Console.WriteLine(Regex.IsMatch(value, "carrot"));
    }
}

Output

True
False

Summary

Programming tip

The RegexOptions.IgnoreCase enumerated constant is simple in its intent and also its application: it will relax the requirements for an input with letters to be matched. Thus, the input string can have a capital or lowercase letter, and the regular expression that only specifies a lowercase letter will still succeed. I have found the RegexOptions.IgnoreCase argument to be useful in many regular expressions.

Regex Type
.NET