基于过程:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace RegexpTest
{
class Program
{
static void Main(string[] args)
{
string text = "the quick red fox jumped over the lazy brown dog.";
Console.WriteLine("text=[" + text + "]");
string result = "";
string pattern = @"\w+|\W+";
foreach (Match m in Regex.Matches(text, pattern)) //Match: 一次表达式的匹配结果,由Group继承而来;Matches: 返回一系列的Match的方法;
{
// 取得匹配的字符串
string x = m.ToString();
// 如果第一个字符是小写
if (char.IsLower(x[0]))
// 变成大写
x = char.ToUpper(x[0]) + x.Substring(1, x.Length - 1);
// 收集所有的字符
result += x;
}
Console.WriteLine("result=[" + result + "]");
Console.ReadKey();
}
}
}
基于表达式方法:
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.";
Console.WriteLine("text=[" + text + "]");
string pattern = @"\w+";
string result = Regex.Replace(text, pattern, new MatchEvaluator(CapText));
Console.WriteLine("result=[" + result + "]");
Console.ReadKey();
}
|