How to use the Regex class to check for string with case insensitive?

I’m a little stuck on this one, and I’m sure it’s actually very easy to do…but I am missing something.

Basically I need to check for a string, but without case sensitive:

string input = "Track 01";

if( input == "track 01")
{
  //do something
}

right now the above if statement returns false, because I should be looking for a capital “T”. What i want to do is make the above if statement return true whether the input is “Track 01” or “track 01”, or even better, “track01”.

I looked at the Regex class on the MSN library but I’m a little confused as to how I would use it in my scenario? I guess I don’t really understand the tutorials on the use of the Regex class.

I have also read that “(?i)” before the string is the same as using RegexOptions.IgnoreCase flag, but again, I couldn’t make it work.

Any help would be greatly appreciated!
Thanks

1 Like

Put this at the top of your file …

using System.Text.RegularExpressions;

And then do your comparison like this …

string input = "Track 01";

if( Regex.IsMatch(input, "track 01", RegexOptions.IgnoreCase) )
{
  //do something
}

Note that any string containing the “track 01” pattern will also match. If you want to match the entire string you need to anchor the pattern to the start and end of the line, with “^track 01$”. Regular expressions are a complex language of their own – powerful, but not always intuitive.

If all you want is case-insensitive comparison then this is much simpler:

if( String.Compare(input, "track 01", true) )
{
  // do something
}