使用Regex.Replace中的MatchEvaluator

在 .net 中的 Regular Expression, 是使用這個 namespace: System.Text.RegularExpressions

其中若是要做比對樣式的內容取代, 可以使用 MatchEvaluator, 來進行將比對的內容進行處理再替代回去. 例如將 Server.UrlEncode 後的 %2f 改為 %2F, 而其他部分不要異動大小寫時, 就很實用.

程式碼如下:

using System.Text.RegularExpressions;

string value = "http://www.google.com";
value = Server.UrlEncode(value);
value = Regex.Replace(value, "(%[0-9a-f][0-9a-f])", delegate(Match match) { return match.ToString().ToUpper();});
Response.Write(value);

其中 Server.UrlEncode 出來的結果為: http%3a%2f%2fwww.google.com , 而利用了 Regex.Replace 配合 MatchEvaluator 後, 就改為 http%3A%2F%2Fwww.google.com , 這樣只有改到 %xx 這種的大小寫, 而不會影響原來的大小寫.

其中的 MatchEvaluator 是一個 delegate 就是用來做每個比對到的內容再做加工的處理, 這裡用了類似 javascript 中的暱名函數處理, 把 MatchEvaluator 直接 inline 寫在裡面. 其中的 System.Text.RegularExpressions.Match 還有許多屬性可以, 例如 Index 可以取出是第幾個比對到的, 可以參考: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match_members.aspx

這樣一來是不是變得很容易處理字串, 另外也要注意有關的效率問題, 一定要顧及, 否則在大量文字比對後, 又利用了 MatchEvaluator 來進行處理, 若該函數效率不好, 會大打折扣的.

參考資料:
http://dotnetperls.com/regex-replace

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *