盾怪网教程:是一个免费提供流行杀毒软件教程、在线学习分享的学习平台!

解读C#中的正则表达式

时间:2024/10/28作者:未知来源:盾怪网教程人气:

[摘要]\W+";   foreach (Match m in Regex.Matches(text, pattern))      // 取得匹配的字符串 ...
\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#环境中使用规则表达式,我写出一些对你来说可能有用的规则表达式,这些表达式在其他的环境中都被使用过,希望能够对你有所帮助。
  
罗马数字

string p1 = "^m*(d?c{0,3}

关键词:解读C#中的正则表达式




Copyright © 2012-2018 盾怪网教程(http://www.dunguai.com) .All Rights Reserved 网站地图 友情链接

免责声明:本站资源均来自互联网收集 如有侵犯到您利益的地方请及时联系管理删除,敬请见谅!

QQ:1006262270   邮箱:kfyvi376850063@126.com   手机版