Regex入门(一)

Regex入门(一)

平时正则表达式接触的比较多,但是大多数都是走马观花形式的,要了去搜索,看了就忘。今天温习了下,把成果写出来,做个总结:

下面介绍的都是简单的用法,复杂点的明天继续,呵呵:

Regex. IsMatch用法

 //简单匹配某单词

            Console.WriteLine("\n\nIsMatch演示:");
            Regex reg 
= new Regex("aaron");
            Console.WriteLine(
string.Format("result1: {0}", reg.IsMatch("my name is aaron.")));     //True
            Console.WriteLine(string.Format("result2: {0}", reg.IsMatch("my name is arron.")));     //False

 //默认是区分大小写的,所以下面2个会返回不同的结果

            Console.WriteLine(string.Format("result3: {0}", Regex.IsMatch("my name is aaron.""Aaron")));      //False
            Console.WriteLine(string.Format("result4: {0}", Regex.IsMatch("my name is arron.""aaron")));      //False

 //这个是不区分大小写的

            Console.WriteLine(string.Format("result3: {0}", Regex.IsMatch("my name is aaron.""Aaron", RegexOptions.IgnoreCase)));     //True

Regex. Replace用法

简单替换某单词

//简单替换某单词
            Console.WriteLine("\n\nReplace演示:");
            reg
=new Regex("r");
            Console.WriteLine(
string.Format("result4: {0}", reg.Replace("my name is arron.""R")));                            //my name is aRRon.
            Console.WriteLine(string.Format("result4: {0}", reg.Replace("my name is arron.""R"1)));//只进行一次替换         //my name is aRron.

Regex.Match用法

 //**********************Match用法*****************************

            Console.WriteLine("\n\nMatch演示:");
            reg 
= new Regex("aa...");//开头2个字母必须是aa,并且后面跟任意3个字符
            Match m=reg.Match("my name is aaron, aaRON, Aaron");
            
while(m.Success)
            {
                Console.WriteLine(m.Value);
                m 
= m.NextMatch();
                
//这里由于默认是区分大小写的,所以
                
//  aaron       是Match的
                
//  aaRON       也是Match的
                
//  Aaron       不会Match
            }

Regex.Matchs用法

//******************MatchsCollection用法***********************
            Console.WriteLine("\n\nMatchsCollection演示:");
            MatchCollection mc 
= Regex.Matches("my name is aaron, aaRON, Aaron""aa...");//开头2个字母必须是aa,并且后面跟任意3个字符

            Console.WriteLine(string.Format("found: {0}", mc.Count)); 

原文地址:https://www.cnblogs.com/aarond/p/2041554.html