RegexOptions.IgnoreCase
Sometimes text data has inconsistent casing. Some data is uppercase, and some lowercase, but both are valid.
Enum
infoThe Regex
type in the C# language by default is case-sensitive. But RegexOptions.IgnoreCase
, an enum
value, relaxes this.
The RegexOptions
enum
is a Regex
argument. This example shows how RegexOptions.IgnoreCase
affects the result of the IsMatch
method on an input that is in a different case.
IgnoreCase
is specified, the match succeeds. Otherwise it fails. IgnoreCase
will relax the regular expression.using System; using System.Text.RegularExpressions; // 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"));True False
You can use RegexOptions.IgnoreCase
with other methods, not just IsMatch
. Try it with Split
, Matches
and Match
. It has the same effect when used with these methods.
RegexOptions.IgnoreCase
will relax the requirements for an input with letters to be matched. Thus, the input string can have a capital or lowercase letter.
The RegexOptions.IgnoreCase
argument is useful in many regular expressions. Before using ToLower()
, consider using IgnoreCase
.