Is there an alternative to string.Replace that is case
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?
From MSDN
$0 - "Substitutes the last substring matched by group number number (decimal)."
In .NET Regular expressions group 0 is always the entire match. For a literal $ you need to
string value = Regex.Replace("%PolicyAmount%", "%PolicyAmount%", @"$$0", RegexOptions.IgnoreCase);
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();
}
Here's an extension method. Not sure where I found it.
public static class StringExtensions
{
public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
{
int startIndex = 0;
while (true)
{
startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
if (startIndex == -1)
break;
originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);
startIndex += newValue.Length;
}
return originalString;
}
}
链接地址: http://www.djcxy.com/p/21024.html
上一篇: 将字符串转换为标题大小写
下一篇: 有没有替代字符串。替换是大小写