- Home /
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
Answer by yoyo · May 31, 2011 at 05:05 AM
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
}
Awesome, thx a lot yoyo! I just started scratching the surface of Regular expressions and yes, they are a complex language which confuses the heck out of me haha.
Your answer was exactly what I needed, very clear and easy to follow, thanks again!
how would i check that the user has pressed the enter/return key? I've tried using
if(Regex.Is$$anonymous$$atch(stringToEdit, "done")){
but it doesn't work. using a letter such as z does what i want so the rest of the code is fine, i just cannot figure out the shortcut for the enter key. I've also tried using fire 2 and setting that up in the input manager to be enter but that doesn't work either
I know I am quite late to the party on this one but for anyone else that stumbles across this question/answer and wants a little more information about Regex expressions and usage check out this interactive tutorial series which $$anonymous$$ches a good portion of the hows with this amazing little engine. https://regexone.com/lesson/introduction_abcs
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
check guitexture 2 Answers