正则替换字符时,同时替换不同的字符

1、场景1 替换单纯收个字母大写

调用

    string s1 = "samuel allen";  

    string changestr=TextTools.UpperFirst(s1)

类方法

    public static class TextTools     {         /// <summary>         /// Uppercase first letters of all words in the string.         /// </summary>         public static string UpperFirst(string s)         {             return Regex.Replace(s, @"\b[a-z]\w+", delegate(Match match)             {                 string v = match.ToString();                 return char.ToUpper(v[0]) + v.Substring(1);             });         }     }

2、将字符串转换成xml认识的字符

调用:

private void button2_Click(object sender, EventArgs e)         {

            string str = "<You're angle & evil>";             string pattern = "'|&|<|>";

            Regex regex = new Regex(pattern);             MatchEvaluator evaluator = new MatchEvaluator(ConvertToXML);             Console.WriteLine(regex.Replace(str, evaluator));             Console.Read();

        }         //把正则表达式的匹配到的字符转换成xml能正常识别的标识         public string ConvertToXML(Match m)         {             switch (m.Value)             {                 case "'":                     return "&apos";                 case "&":                     return "&amp";                 case "<":                     return "&lt";                 case ">":                     return "&gt";                 default:                     return "";             }

        }

posted @ 2012-07-05 13:43  刘颖  阅读(191)  评论(0编辑  收藏