正则表达式

var someText = "web2.0 .net2.0";
        var pattern = /(\w+)(\d)\.(\d)/;
        var outCome_exec = pattern.exec(someText); //类似数组的返回值 [web2.0, web, 2, 0]
        var outCome_matc = someText.match(pattern);//类似数组的返回值 [web2.0,web,2,0]
 
        var pattern2 = /(\w+)(\d)\.(\d)/g;
        var outCome_exec2 = pattern2.exec(someText);//类似数组的返回值 [web2.0, web, 2, 0]
        var outCome_matc2 = someText.match(pattern2);//类似数组的返回值 [web2.0,net2.0]
/*如果正则表达式没有g参数,那么exec和match效果一样*/
 
C#

String someText = "web2.0 .net2.0";
            Regex pattern =new Regex(@"(\w+)(\d)\.(\d)");
 
            pattern.Match(someText).Value;
            /*Match方法相当于没有g参数的正则表达式使用exec方法。 Match返回一个
              数组,可以通过pattern.Match(someText).Group访问;(这里的Group.Count=4)
            */
             pattern.Match(someText).Groups[0].Value //得到web
 
           
            pattern.Matches(someText);
            /*相当于加了g参数使用match方法。
                pattern.Matches(someText).Count==2
                pattern.Matches(someText)[0].Value=web2.0;
              pattern.Matches(someText)[1].Value=net2.0;
              有意思的是pattern.Matches(someText)[0].Group.Count=4;
              感觉就像 pattern.Match("web2.0").Group.Count 一样
             */

 

String someText = "web2.0 .net2.0";
            Regex pattern =new Regex(@"(\w+)(\d)\.(\d)");
 
            Match m2 = pattern.Match(someText);
            while (m2.Success)//这里会循环2次,第一次为web2.0 ,第二次是net2.0 因为Match方法相当于exec方法
            {
                Console.WriteLine("match  "+m2.Value);
 
                for (int i = 0; i < m2.Groups.Count; i++)
                {
                    Console.WriteLine("\t" + m2.Value + " group " + i.ToString() + "  " + m2.Groups[i].Value);
 
                    for (int j = 0; j < m2.Groups[j].Captures.Count; j++)
                    {
                        Console.WriteLine("\t\t" + m2.Value + " Captures " + j.ToString() + "  " + m2.Groups[i].Captures[j].Value); ;
                    }
                }
                m2= m2.NextMatch();
            }

 

string.replace(reg, expression | function) 方法

var strM = "javascript is a good script language";
        alert(strM.replace(/(\w+)\b/g, function($0, $1) {
            return $1.toString().substr(0, 1).toUpperCase() + $1.toString().slice(1);
        }));
        function mask_HTMLCode(strInput) {  
          var myReg = /<(\w+)>/;  
          return strInput.replace(myReg, "&lt;$1&gt;");  
        }  
/*
第一个方法为把所有单词首字母大写
第二个方法过滤掉html标签
如果第一个参数正则表达式没有加 g 参数,那么只会匹配第一项。
*/
posted @ 2010-07-01 16:43  MyCoolDog  阅读(223)  评论(0编辑  收藏  举报