C#实现的ReplaceFirst和ReplaceLast

时间:2021-12-10 17:57:55

原文:C#实现的ReplaceFirst和ReplaceLast

ReplaceFirst:

public static string ReplaceFirst(string input, string oldValue, string newValue)
{
Regex regEx = new Regex(oldValue, RegexOptions.Multiline);
return regEx.Replace(input, newValue==null?"":newValue, 1);

}

注意:如果替换的旧值中有特殊符号,替换将会失败,解决办法 例如特殊符号是“(”: 要在调用本方法前加oldValue=oldValue.Replace("(","//(");

ReplaceLast:

public static string ReplaceLast(string input, string oldValue, string newValue)
{
int index = input.LastIndexOf(oldValue);
if (index < 0)
{
return input;
}
else
{
StringBuilder sb = new StringBuilder(input.Length - oldValue.Length + newValue.Length);
sb.Append(input.Substring(0, index));
sb.Append(newValue);
sb.Append(input.Substring(index + oldValue.Length,
input.Length - index - oldValue.Length));

return sb.ToString();
}
}