RegexOptions.IgnoreCase
How can you match a pattern in a regular expression in a case-insensitive way? In .NET we can use the RegexOptions.IgnoreCase
option.
Often, the strings we are processing may have inconsistent casing, with both lowercase and uppercase letters used. We only need one pattern to match these strings with IgnoreCase
.
In the Main
function, we introduce a string
with mixed lowercase and uppercase letters in. Then we try to match this string
with patterns using Regex.IsMatch
.
Regex.IsMatch
with an all-lowercase pattern. We use RegexOptions.IgnoreCase
, and the mixed-case string
is matched.RegexOptions.IgnoreCase
option, and the IsMatch
function returns False, as the cases are not the same.Imports System.Text.RegularExpressions Module Module1 Sub Main() ' String has an uppercase letter. Dim value = "carroT" ' Part 1: use RegexOptions.IgnoreCase with a lowercase pattern. If Regex.IsMatch(value, "carrot", RegexOptions.IgnoreCase) ' This will be printed. Console.WriteLine("IS MATCH!") End If ' Part 2: omit IgnoreCase, so the lowercase pattern will no longer match. Console.WriteLine(Regex.IsMatch(value, "carrot")) End Sub End ModuleIS MATCH! False
In VB.NET programs, the RegexOptions.IgnoreCase
enum
is helpful on many Regex
function calls. It helps make the regular expressions more flexible and useful.