正则表达式编译

正则表达式,是我们在做文本查找和处理时经常用到的。关于它的一些基础知识和教程,请参考下面的一些链接

http://unibetter.com/deerchao/zhengzhe-biaodashi-jiaocheng-se.htm

使用正则表达式并不难,关键就在于编写一个合适的pattern。说到这里,就不得不提一下regexlib这个网站,里面有好多写好的正则表达式。我就经常光顾这个网站,进行一些搜索。据说咱国内也有哥们做了一个类似的网站,地址不记得了

http://regexlib.com/

在.NET里面使用正则表达式,主要就是使用System.Text.RegularExpressions.Regex这个类。具体的用法可以参考帮助文档。

但是,每次都编写pattern,似乎并不是很理想。所以,Regex还提供了一个方法CompileToAssembly,这样,我们就可以把一些常用的表达式编译起来,以便重复使用。为此,我专门写了一个工具

image

以下代码把两个正则表达式编译到E:\Temp\sampleassembly.dll这个程序集中

string outFile = @"e:\temp\sampleassembly.dll";
List<RegexCompilationInfo> infos = new List<RegexCompilationInfo>();
RegexCompilationInfo info = new RegexCompilationInfo(@"\d{5,10}", RegexOptions.Compiled | RegexOptions.IgnoreCase, "Number", "SampleNamespace", true);
infos.Add(info);
infos.Add(new RegexCompilationInfo(@"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$", RegexOptions.IgnoreCase | RegexOptions.Compiled, "Email", "SampleNamespace", true));
System.Reflection.AssemblyName an = new System.Reflection.AssemblyName(System.IO.Path.GetFileNameWithoutExtension(outFile));
string currentDir = Environment.CurrentDirectory;
Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(outFile); //切换一下当前目录的目的是使得编译的时候,可以把程序集放到相应的目录中去
Regex.CompileToAssembly(infos.ToArray(),an);
Environment.CurrentDirectory = currentDir;

编译好之后,在客户程序中使用的话,大致是这样的:

1. 添加对程序集的引用

2. 实例化里面的类型,然后调用相关方法。例如

SampleNamespace.Number numberRegex = new SampleNamespace.Number();
MessageBox.Show(numberRegex.IsMatch("12345").ToString());

值得注意的是,因为正则表达式的pattern已经被编译到了程序集,所以这边的IsMatch方法只需要输入需要验证的文本即可。

 

另外,在编写这个小工具的时候,偶然发现有一个哥们已经写了一个Console App,也是做这个事情的。下面链接可以供参考

http://www.codeplex.com/RegexC

posted @ 2008-07-26 21:58  陈希章  阅读(1970)  评论(1编辑  收藏  举报