views:

219

answers:

2

I have written the following code to do case insensitive replace in C#:

Regex.Replace(textBoxText, 
    Regex.Escape(findText), 
    replaceText, 
    RegexOptions.IgnoreCase);

Just wanted to check, whether this is the right approach, or is there a better approach and whether I'm overlooking something that I should better be aware of.

Note: Please don't provide me some hand crafted code, I had used a fast replace function from codeproject, and that code crashes at client side, and I have no way to know, what input the user was using. So, I prefer some simple but correct and reliable method.

A: 

Seems OK to me. Does it work in all cases you need? If it does - use it.

Thorsten Dittmar
hey, that's what I wanted to know, whether it cover all cases or not. That is the question :)
Priyank Bolia
You asked whether this was the right approach or if there was something better (not including hand-crafted code). So saying that using Regex.Replace as you did seems ok for me and should be ok for you as long as it covers what you need seems a perfectly good answer to me. It is virtually impossible to say whether some approach covers ALL possible cases.
Thorsten Dittmar
+4  A: 
Abel
I didn't get this part: 'but that it is not possible to switch case-sensitivity'? Also how to set the locale for comparison?
Priyank Bolia
Sorry, was interrupted by a phone call and hit submit too quickly. See my edits, it answers both your questions, I think.
Abel
the regex is basically user input which is escaped, so that it won't ask like an invalid regex sometimes. So, I think RegexOptions.CultureInvariant is the better choice. Also I am looking for English only.
Priyank Bolia
Then `CultureInvariant` is the way to go as there are few differences (if any) with English. You can also explicitly set the culture to British or Am. English as described above. Obviously, if you use `Regex.Escape`, users cannot use any regular expression powers, it's just a string. No need for regexes anymore. Just use `String.Replace`, which will give you better performance (and also case-insensitivity).
Abel
"Just use String.Replace, which will give you better performance (and also case-insensitivity)." -- Does String.Replace provide case-insensitivity, I don't think so.
Priyank Bolia
My apologies, you are absolutely right! I was confused with the comparison switches. You need to use `ToLowerInvariant`, but then you change the whole string, which may not be what you want.
Abel