| string text = "the quick red fox jumped over the lazy brown dog."; System.Console.WriteLine("text=[" + text + "]"); string result = ""; string pattern = @"\w+|\W+"; foreach (Match m in Regex.Matches(text, pattern)) { // 取得匹配的字符串 string x = m.ToString(); // 如果第一个字符是小写 if (char.IsLower(x[0])) // 变成大写 x = char.ToUpper(x[0]) + x.Substring(1, x.Length-1); // 收集所有的字符 result += x; } System.Console.WriteLine("result=[" + result + "]"); |
| text=[the quick red fox jumped over the lazy brown dog.] result=[The Quick Red Fox Jumped Over The Lazy Brown Dog.] |
| static string CapText(Match m) { //取得匹配的字符串 string x = m.ToString(); // 如果第一个字符是小写 if (char.IsLower(x[0])) // 转换为大写 return char.ToUpper(x[0]) + x.Substring(1, x.Length-1); return x; } static void Main() { string text = "the quick red fox jumped over the lazy brown dog."; System.Console.WriteLine("text=[" + text + "]"); string pattern = @"\w+"; string result = Regex.Replace(text, pattern, new MatchEvaluator(Test.CapText)); System.Console.WriteLine("result=[" + result + "]"); } |