正则表达式 小结

正则表达式是一种文本模式,经常被用来匹配具有某种规则的文本。 正则表达式可以写得很复杂,内容也可以很高深,但是常用的规则很简单。本文主要小结一下最近用到的正则表达式语法,足以满足平常的小需求了。

首先先了解一下基本单元:特殊字符与元字符。  http://msdn.microsoft.com/zh-cn/library/ae5bf541(v=vs.100).aspx 这篇文章中有详细的参考清单。

特殊字符就是它本身不匹配某种单词,但是它有辅助含义,比如 ^表示当前模式一定要出现在文本的开头,$表示文本的结尾, +表示该模式出现一次或者多次。

元字符表示匹配某种单词,比如\d表示数字,即[0-9],\w表示A-Z、a-z、0-9 和下划线。

熟悉了特殊字符和元字符之后,就来看看一些实例吧。

要匹配类似“2014-9-10” 这样固定格式的时间字符串:  @"\d+4\-\d{1,2}\-\d{1,2}"  前面的@是c#的符号。

要匹配类似"Sep 4"的时间格式:   @"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{1,2}"

最后举一个c#的实例

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             Regex regex = new Regex(@"^\(CNN\) (Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)[\s|\S]*\.$");
 6             string content = @"(CNN) Tuesday he coalition that attacked ISIS in Syria overnight ""makes it clear to the world that this is not America's fight alone,"" U.S. President Barack Obama said Tuesday.";
 7             string content2= @"(CNN) Tuesday he coalition that attacked ISIS in Syria overnight ""makes it clear to the world that this is not America's fight alone,"" U.S. President Barack Obama said Tuesday.hehe";
 8             Console.WriteLine(regex.IsMatch(content));
 9             Console.WriteLine(regex.IsMatch(content2));
10 12             Console.ReadKey();
13         
14         }
15     }

 

 

  

posted on 2014-09-24 00:16  leavingseason  阅读(561)  评论(0编辑  收藏  举报

导航

Bye!