C#正则表达式Regex类的使用

C#中为正则表达式的使用提供了非常强大的功能,这就是Regex类。这个包包含于System.Text.RegularExpressions命名空间下面,而这个命名空间所在DLL基本上在所有的项目模板中都不需要单独去添加引用,可以直接使用。

1、定义一个Regex类的实例


Regex regex = new Regex(@"\d");
这里的初始化参数就是一个正则表达式,“\d”表示配置数字。

2、判断是否匹配

判断一个字符串,是否匹配一个正则表达式,在Regex对象中,可以使用Regex.IsMatch(string)方法。

regex.IsMatch("abc"); //返回值为false,字符串中未包含数字
regex.IsMatch("abc3abc"); //返回值为true,因为字符串中包含了数字

3、获取匹配次数

使用Regex.Matches(string)方法得到一个Matches集合,再使用这个集合的Count属性。

regex.Matches("abc123abc").Count; 
返回值为3,因为匹配了三次数字。

4、获取匹配的内容

使用Regex.Match(string)方法进行匹配。

regex.Match("abc123abc").Value;
返回值为1,表示第一个匹配到的值。

5、捕获

正则表达式中可以使用括号对部分值进行捕获,要想获取捕获的值,可以使用Regex.Match(string).Groups[int].Value来获取。

Regex regex = new Regex(@"\w(\d*)\w"); //匹配两个字母间的数字串
regex.Match("abc123abc").Groups[0].Value; //返回值为“123”。

 

using System;  
using System.Text.RegularExpressions;   
namespace Magci.Test.Strings  
{      
    public class TestRegular      
    {          
        public static void WriteMatches(string str, MatchCollection matches)          
        {              
            Console.WriteLine("\nString is : " + str);              
            Console.WriteLine("No. of matches : " + matches.Count);              
            foreach (Match nextMatch in matches)              
            {                  
                //取出匹配字符串和最多10个外围字符                  
                int Index = nextMatch.Index;                  
                string result = nextMatch.ToString();                  
                int charsBefore = (Index < 5) ? Index : 5;                  
                int fromEnd = str.Length - Index - result.Length;                  
                int charsAfter = (fromEnd < 5) ? fromEnd : 5;                  
                int charsToDisplay = charsBefore + result.Length + charsAfter;                   
                Console.WriteLine("Index: {0},\tString: {1},\t{2}", Index, result, str.Substring(Index - charsBefore, charsToDisplay));             
            }          
        }           
        
        public static void Main()          
        {              
            string Str = @"My name is Magci, for short mgc. I like c sharp!";               
            //查找“gc”              
            string Pattern = "gc";              
            MatchCollection Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);               
            WriteMatches(Str, Matches);                            
            //查找以“m”开头,“c”结尾的单词              
            Pattern = @"\bm\S*c\b";              
            Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);               
            WriteMatches(Str, Matches);          
        }      
    }  
} 

 

http://www.splaybow.com/csharp-regex-class.shtml

http://developer.51cto.com/art/200908/144164.htm

分类:

技术点:

相关文章: