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?
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 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.
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With