Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative to string.Replace that is case-insensitive?

I need to search a string and replace all occurrences of %FirstName% and %PolicyAmount% with a value pulled from a database. The problem is the capitalization of FirstName varies. That prevents me from using the String.Replace() method. I've seen web pages on the subject that suggest

Regex.Replace(strInput, strToken, strReplaceWith, RegexOptions.IgnoreCase); 

However for some reason when I try and replace %PolicyAmount% with $0, the replacement never takes place. I assume that it has something to do with the dollar sign being a reserved character in regex.

Is there another method I can use that doesn't involve sanitizing the input to deal with regex special characters?

like image 589
Aheho Avatar asked Oct 28 '08 19:10

Aheho


People also ask

Is string replace case-sensitive?

Introduction. The String. Replace() method allows you to easily replace a substring with another substring, or a character with another character, within the contents of a String object. This method is very handy, but it is always case-sensitive.

Is Python string replace case-sensitive?

Is the String replace function case sensitive? Yes, the replace function is case sensitive. That means, the word “this” has a different meaning to “This” or “THIS”. In the following example, a string is created with the different case letters, that is followed by using the Python replace string method.

Does string contain case-sensitive?

The string. Contains() method in C# is case sensitive. And there is not StringComparison parameter available similar to Equals() method, which helps to compare case insensitive.


1 Answers

Seems like string.Replace should have an overload that takes a StringComparison argument. Since it doesn't, you could try something like this:

public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison) {     StringBuilder sb = new StringBuilder();      int previousIndex = 0;     int index = str.IndexOf(oldValue, comparison);     while (index != -1)     {         sb.Append(str.Substring(previousIndex, index - previousIndex));         sb.Append(newValue);         index += oldValue.Length;          previousIndex = index;         index = str.IndexOf(oldValue, index, comparison);     }     sb.Append(str.Substring(previousIndex));      return sb.ToString(); } 
like image 107
C. Dragon 76 Avatar answered Oct 05 '22 23:10

C. Dragon 76