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)); 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值