谈谈C# replace在正则表达式中的意义

2019-12-30 11:41:57刘景俊

基于过程的模式

  我们在编程中经常需要用到的一个功能是对字符串中的一部分进行匹配或其他一些对字符串处理,下面是一个对字符串中的单词进行匹配的例子:


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 + "]");

  正象上面的例子所示,我们使用了C#语言中的foreach语句处理每个匹配的字符,并完成相应的处理,在这个例子中,新创建了一个result字符串。这个例子的输出所下所示: 


  text=[the quick red fox jumped over the lazy brown dog.] 
  result=[The Quick Red Fox Jumped Over The Lazy Brown Dog.] 

基于表达式的模式

  完成上例中的功能的另一条途径是通过一个MatchEvaluator,新的代码如下所示: 


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 + "]"); 
    } 

  同时需要注意的是,由于仅仅需要对单词进行修改而无需对非单词进行修改,这个模式显得非常简单。

常用表达式

  为了能够更好地理解如何在C#环境中使用规则表达式,我写出一些对你来说可能有用的规则表达式,这些表达式在其他的环境中都被使用过,希望能够对你有所帮助。