[ASP.NET] Replace 字串的幾種方法
這幾天有一個Task是一個很常見的Task ,
就是搜尋關鍵字,但是要把搜尋出來的關鍵字做highlight ,
所以順便寫了一些比較常見的Replace方法,來記錄一下
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
public partial class testReplace : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string str = "Test,TEST,teSt,tesT,test";
string replaceStr = "test";
Response.Write("(1)正常:" + str);
Response.Write("(2)一般Replace:" + str.Replace(replaceStr, "" + replaceStr + ""));
Response.Write("(3)忽略大小寫Replace1:" + Regex.Replace(str, replaceStr, "" + replaceStr + "", RegexOptions.IgnoreCase));
Response.Write("(4)忽略大小寫Replace2:" + HighlightString(str, replaceStr));
}
protected string HighlightString(string Contents, string ReplaceWord)
{
System.Text.RegularExpressions.MatchCollection matchs = Regex.Matches(Contents, ReplaceWord, RegexOptions.IgnoreCase);
for (int i = 0; i < matchs.Count; i++)
{
Contents = Regex.Replace(Contents, matchs[i].Value, "" + matchs[i].Value + "");
}
return Contents;
}
}
顯示的結果如下