Case-Insensitive Regex Patterns in .NET

by bob on June 28, 2008

For some reason, I haven’t had to do this in a long time, so had to look it up.

There are three options for doing case-insensitive regular expressions in .NET.

The first is to use the RegexOptions enumeration to specify case-insensitive behavior:

Regex.IsMatch("Fubar","^fubar",RegexOptions.IgnoreCase)

The equivalent option is to put (?i) at the start of the expression. This is useful if you want to feed data-driven patterns to the matching engine and control from the expression whether it’s case insensitive or not:

Regex.IsMatch("Fubar","(?i)^fubar")

Lastly, you can put part of an expression in a group and specify that only that part is to be case insensitive. In this example, Fubar is matched case sensitive but FOO is not:

Regex.IsMatch("Fubar Foo","^Fubar (?i:FOO)")

Leave a Comment

Previous post:

Next post: