Leo's Blog

這裡只是平常工作的一些小筆記和小心得,歡迎給予指教
文章數 - 31, 回應數 - 56, 引用數 - 0

文章標籤

全部標籤

每月文章

文章分類

[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;
    }
}

顯示的結果如下



DotBlogs Tags: C# Regex Replace 大小寫

posted on 2011/11/2 19:16 1 人推薦 我要推薦 | 閱讀數 : 3433 | 文章分類 [ ASP.NET ] 訂閱

Feedback

目前沒有回應.

回應

標題
姓名
電子郵件 (將不會被顯示)
個人網頁
內容 
  登入後使用進階評論  
Please add 4 and 3 and type the answer here:

Powered by: