C#正则表达式 — 正则表达式类

来自:http://www.dreamdu.com/blog/2008/10/07/cs_regex_class/

C#正则表达式 — 正则表达式类

又重新学了一遍C#的正则表达式,温故而知新,C#的正则就用一句话概括吧:很好很强大! 这里做个笔记,笔记的相关内容多数摘自MSDN。

Regex 类表示不可变(只读)的正则表达式。它还包含各种静态方法,允许在不显式创建其他类的实例的情况下使用其他正则表达式类。

Match 类表示正则表达式匹配操作的结果。Match 类的 Match.Success 匹配是否成功。Match.Index 返回第一个匹配的位置。

MatchCollection 类表示成功的【非重叠】匹配项的序列。MatchCollection 的实例是由 Regex.Matches 方法返回的。

GroupCollection 类表示被捕获的组的集合,并在单个匹配项中返回该捕获组的集合。GroupCollection 的实例在 Match.Groups 属性返回的集合中返回。

CaptureCollection 类表示捕获的子字符串的序列,并返回由单个捕获组所执行的捕获集。由于限定符,捕获组可以在单个匹配中捕获多个字符串。Captures 属性(CaptureCollection 类的对象)作为 Match 和 Group 类的成员提供,目的是便于对捕获的子字符串的集合进行访问。

Group 类表示来自单个捕获组的结果。因为 Group 可以在单个匹配中捕获零个、一个或更多的字符串(使用限定符),所以它包含 Capture 对象的集合。因为 Group 继承自 Capture,所以可以直接访问最后捕获的子字符串(Group 实例本身等价于 Captures 属性返回的集合的最后一项)。

Capture 类包含来自单个子表达式捕获的结果。

为了更好地理解上面类的相互关系,我把msdn的示例扩展了一下:

using System;
using System.Text.RegularExpressions;

/// <summary>
/// 2008-10-07 copyright 可爱的猴子
/// http://www.dreamdu.com/blog/
/// </summary>
public class RegexTest
{
   public static void Main()
   {
	   Regex r = new Regex("(Abc)+");
	   string str = "XYZAbcAbcAbcXYZAbcAb";
	   MatchCollection mc = r.Matches(str);
	   Console.WriteLine("---------------------Group-------MatchCollection={0}", mc.Count);
	   foreach (Match mt in mc)
	   {
		   Console.WriteLine("match = {0}", mt.Value);
		   Console.WriteLine("--------------Group={0}", mt.Groups.Count);
		   foreach (Group gc in mt.Groups)
		   {
			   Console.WriteLine("Group value is:{0}.    Index is:{1}",
gc.Value, gc.Index);
			   Console.WriteLine("-------Gapture={0}",
gc.Captures.Count);
			   foreach (Capture gg in gc.Captures)
			   {
				   Console.WriteLine("Capture value is:{0}.  Index is:{1}",
gg.Value, gg.Index);
			   }
		   }
	   }

	   Console.WriteLine("---------------------Capture-------MatchCollection={0}",
mc.Count);
	   foreach (Match mt in mc)
	   {
		   Console.WriteLine("match = {0}",
mt.Value);
		   Console.WriteLine("--------------Capture={0}",
mt.Captures.Count);
		   foreach (Capture gc in mt.Captures)
		   {
			   Console.WriteLine("Group value is:{0}.    Index is:{1}",
gc.Value, gc.Index);
		   }
	   }

	   Match m = r.Match(str);
	   GroupCollection gcc = m.Groups;
	   Console.WriteLine("--------------------------------GroupCollection={0}",
gcc.Count);
	   foreach (Group gt in gcc)
	   {
		   CaptureCollection cc = gt.Captures;

		   Console.WriteLine("--------------Captures={0}",
cc.Count);
		   foreach (Capture ccnp in gt.Captures)
		   {
			   Console.WriteLine("Capture value is:{0}.    Index is:{1}",
ccnp.Value, ccnp.Index);
		   }
	   }

	   CaptureCollection ccn = m.Captures;
	   Console.WriteLine("--------------------------------CaptureCollection={0}",
ccn.Count);
	   foreach (Capture gt in ccn)
	   {
		   Console.WriteLine("Capture value is:{0}.    Index is:{1}",
gt.Value, gt.Index);
	   }
   }
}

通过上面这个例子应该可以看出这几个类的实例的关系了,其实也很简单,就是互相包含的关系。

posted @ 2009-08-05 10:11  s80895304  阅读(647)  评论(0编辑  收藏  举报