原文: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();
}
}

最新文章

  1. Sublime中Markdown的安装与使用
  2. mysql中常用的控制流函数
  3. Oracle基础和用户管理
  4. 设置arc/非arc
  5. Core love JavaScript
  6. Unity光照图UV显示
  7. 关于dialog引起的 java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView not attached to window manager 错误的分析
  8. os8 location authorization 错误.
  9. 由MyEclipse内存不足谈谈JVM内存设置
  10. Winform获取当前程序名称或路径
  11. javascript中的==与===
  12. Maven服务器
  13. loadrunner脚本函数讲解
  14. vs 为什么使用#include &quot;stdafx.h&quot;
  15. C#导入c++ dll报找不到dll文件 masm32调用c++类库
  16. Java入门系列 Java 中的四种引用
  17. Matlab入门笔记(1)
  18. print()与println()区别
  19. myeclipse debug模式 报错source not found
  20. checkbox选中事件

热门文章

  1. tomcat6.0 数据库连接池配置问题
  2. 每日一“酷”之textwrap
  3. PAT IO-03 整数均值
  4. Posix 共享内存区
  5. mac安装cocoapods
  6. STL学习一:标准模板库理论基础
  7. C语言中的字符串拷贝函数strcpy和内存拷贝函数memcpy的区别与实现
  8. 日志文件切割服务logrotate配置及crontab定时任务的使用
  9. Sublime Text 2 入门
  10. Java 执行 SQL 脚本文件