使用正则表达式提可以使我们灵活而又高效的处理文本。
正则表达式的全面模式匹配表示法可以使我们快速地分析大量的文本以找到特定的字符模式;提取、编辑、替换或删除文本子字符串;或将提取的字符串添加到集合以生成报告。
如果你对正则表达式还不了解,你可以看看以前发表的文章,有许多关于正则表达式入门的文章,本文不对正则表达式的使用进行介绍。本文主要给出了我自己做的一个正则表达式的测试例子,测试.net下的正则表达式。
由于我前一段时间总和正则表达式打交道,参考了不少前面的文章,也从网友的那里解决了不少问题,所以向回报一下大家。和写完一个程序我们总要测试一下一样,每写一个正则表达式我也总是要测试以下它的正确性,使用VS的单步跟踪能力可以对自己写的式子逐个测试,可是效率太低。于是自己就写了一个测试程序(使用C#开发,VS2003)暂时定名为RegexTester,下面是界面的一个截图:
界面参考了一本书上的一个例子,是不是还比较容易理解。
在窗体的右下角有Regex对应的各种方法的按钮,点击相应按钮你就可以得到相应的结果。
在程序中我采用了TreeView控件用来显示Match和Matches的层次结构。对于Replace和Split的结果采用文本框显示。TreeView控件和文本框控件在同一个位置,通过相应的显隐来显示相应的结果。
你觉得:[1-4[a-b]hj]abc它能匹配什么?
2\d{3}(0[1-9])|(1[12])能正确找到类似200404这样的年月组合吗?
如果你不确定就要该程序测试一下把!
哈哈,通过该程序你也可以检查论坛中网友给的结果是否正确。
由于我不知道程序该保存到那里,所以就把源代码全贴出来了,源代码分为两个文件frmRegexTester为窗体文件。RegexTest为进行处理的类文件。
下面全是这两个文件的代码,注释比较清楚,欢迎多提意见!
/* 程序名 : RegexTester * 用途 : .net下的正则表达式测试程序 * 文件名 : frmRegexTester.cs * 作者 : silverduck * 日期 : 04/05/2004 * e-Mail : [email protected] */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Text.RegularExpressions; namespace RegexTester { ////// 测试程序窗体 /// public class frmRegexTester : System.Windows.Forms.Form { private System.Windows.Forms.Button btnOpenPtn; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox txtPattern; private System.Windows.Forms.GroupBox grpRegOption; private System.Windows.Forms.OpenFileDialog dlgOpen; private System.Windows.Forms.SaveFileDialog dlgSave; private System.Windows.Forms.CheckBox chkIgnoreCase; private System.Windows.Forms.CheckBox chkECMAScript; private System.Windows.Forms.CheckBox chkMultiline; private System.Windows.Forms.CheckBox chkSingleline; private System.Windows.Forms.CheckBox chkIgnorePatternWhitespace; private System.Windows.Forms.CheckBox chkCultureInvariant; private System.Windows.Forms.CheckBox chkRightToLeft; private System.Windows.Forms.CheckBox chkCompiled; private System.Windows.Forms.CheckBox chkExplicitCapture; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox txtTest; private System.Windows.Forms.Panel pnlTest; private System.Windows.Forms.Panel pnlResultTv; private System.Windows.Forms.TreeView tvMatch; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button btnSavePtn; private System.Windows.Forms.Button btnOpenInput; private System.Windows.Forms.Button btnExpand; private System.Windows.Forms.Button btnIsMatch; private System.Windows.Forms.Button btnMatch; private System.Windows.Forms.Button btnSplit; private System.Windows.Forms.Button btnReplace; private System.Windows.Forms.Button btnMatches; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtResult; private System.Windows.Forms.Panel pnlResultTxt; private System.Windows.Forms.TextBox txtReplacement; private System.Windows.Forms.Button btnSaveResult; ////// 必需的设计器变量。 /// private System.ComponentModel.Container components = null; public frmRegexTester() { InitializeComponent(); } ////// 清理所有正在使用的资源。 /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows 窗体设计器生成的代码 ////// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// private void InitializeComponent() { this.btnSavePtn = new System.Windows.Forms.Button(); this.btnOpenPtn = new System.Windows.Forms.Button(); this.label5 = new System.Windows.Forms.Label(); this.btnIsMatch = new System.Windows.Forms.Button(); this.txtPattern = new System.Windows.Forms.TextBox(); this.grpRegOption = new System.Windows.Forms.GroupBox(); this.chkIgnorePatternWhitespace = new System.Windows.Forms.CheckBox(); this.chkCultureInvariant = new System.Windows.Forms.CheckBox(); this.chkRightToLeft = new System.Windows.Forms.CheckBox(); this.chkCompiled = new System.Windows.Forms.CheckBox(); this.chkSingleline = new System.Windows.Forms.CheckBox(); this.chkMultiline = new System.Windows.Forms.CheckBox(); this.chkExplicitCapture = new System.Windows.Forms.CheckBox(); this.chkECMAScript = new System.Windows.Forms.CheckBox(); this.chkIgnoreCase = new System.Windows.Forms.CheckBox(); this.dlgOpen = new System.Windows.Forms.OpenFileDialog(); this.dlgSave = new System.Windows.Forms.SaveFileDialog(); this.pnlTest = new System.Windows.Forms.Panel(); this.btnOpenInput = new System.Windows.Forms.Button(); this.label6 = new System.Windows.Forms.Label(); this.txtTest = new System.Windows.Forms.TextBox(); this.pnlResultTv = new System.Windows.Forms.Panel(); this.btnExpand = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.tvMatch = new System.Windows.Forms.TreeView(); this.btnMatch = new System.Windows.Forms.Button(); this.btnSplit = new System.Windows.Forms.Button(); this.btnReplace = new System.Windows.Forms.Button(); this.btnMatches = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.txtReplacement = new System.Windows.Forms.TextBox(); this.pnlResultTxt = new System.Windows.Forms.Panel(); this.btnSaveResult = new System.Windows.Forms.Button(); this.txtResult = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.grpRegOption.SuspendLayout(); this.pnlTest.SuspendLayout(); this.pnlResultTv.SuspendLayout(); this.groupBox1.SuspendLayout(); this.pnlResultTxt.SuspendLayout(); this.SuspendLayout(); // // btnSavePtn // this.btnSavePtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnSavePtn.Location = new System.Drawing.Point(584, 8); this.btnSavePtn.Name = "btnSavePtn"; this.btnSavePtn.Size = new System.Drawing.Size(88, 23); this.btnSavePtn.TabIndex = 2; this.btnSavePtn.Text = "保存匹配模式"; this.btnSavePtn.Click += new System.EventHandler(this.btnSavePtn_Click); // // btnOpenPtn // this.btnOpenPtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnOpenPtn.Location = new System.Drawing.Point(456, 8); this.btnOpenPtn.Name = "btnOpenPtn"; this.btnOpenPtn.Size = new System.Drawing.Size(96, 23); this.btnOpenPtn.TabIndex = 1; this.btnOpenPtn.Text = "从文件导入(&P)"; this.btnOpenPtn.Click += new System.EventHandler(this.btnOpenPtn_Click); // // label5 // this.label5.Location = new System.Drawing.Point(8, 8); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(112, 16); this.label5.TabIndex = 0; this.label5.Text = "Pattern模式字符串"; // // btnIsMatch // this.btnIsMatch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnIsMatch.Location = new System.Drawing.Point(241, 648); this.btnIsMatch.Name = "btnIsMatch"; this.btnIsMatch.TabIndex = 7; this.btnIsMatch.Text = "IsMatch(&I)"; this.btnIsMatch.Click += new System.EventHandler(this.btnIsMatch_Click); // // txtPattern // this.txtPattern.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtPattern.Location = new System.Drawing.Point(8, 32); this.txtPattern.MaxLength = 32767000; this.txtPattern.Multiline = true; this.txtPattern.Name = "txtPattern"; this.txtPattern.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtPattern.Size = new System.Drawing.Size(672, 56); this.txtPattern.TabIndex = 3; this.txtPattern.Text = ""; // // grpRegOption // this.grpRegOption.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grpRegOption.Controls.Add(this.chkIgnorePatternWhitespace); this.grpRegOption.Controls.Add(this.chkCultureInvariant); this.grpRegOption.Controls.Add(this.chkRightToLeft); this.grpRegOption.Controls.Add(this.chkCompiled); this.grpRegOption.Controls.Add(this.chkSingleline); this.grpRegOption.Controls.Add(this.chkMultiline); this.grpRegOption.Controls.Add(this.chkExplicitCapture); this.grpRegOption.Controls.Add(this.chkECMAScript); this.grpRegOption.Controls.Add(this.chkIgnoreCase); this.grpRegOption.Location = new System.Drawing.Point(8, 88); this.grpRegOption.Name = "grpRegOption"; this.grpRegOption.Size = new System.Drawing.Size(672, 66); this.grpRegOption.TabIndex = 4; this.grpRegOption.TabStop = false; this.grpRegOption.Text = "RegexOptions(正则表达式选项)"; // // chkIgnorePatternWhitespace // this.chkIgnorePatternWhitespace.Checked = true; this.chkIgnorePatternWhitespace.CheckState = System.Windows.Forms.CheckState.Checked; this.chkIgnorePatternWhitespace.Location = new System.Drawing.Point(400, 40); this.chkIgnorePatternWhitespace.Name = "chkIgnorePatternWhitespace"; this.chkIgnorePatternWhitespace.Size = new System.Drawing.Size(168, 24); this.chkIgnorePatternWhitespace.TabIndex = 8; this.chkIgnorePatternWhitespace.Text = "IgnorePatternWhitespace"; // // chkCultureInvariant // this.chkCultureInvariant.Location = new System.Drawing.Point(272, 40); this.chkCultureInvariant.Name = "chkCultureInvariant"; this.chkCultureInvariant.Size = new System.Drawing.Size(128, 24); this.chkCultureInvariant.TabIndex = 7; this.chkCultureInvariant.Text = "CultureInvariant"; // // chkRightToLeft // this.chkRightToLeft.Location = new System.Drawing.Point(144, 40); this.chkRightToLeft.Name = "chkRightToLeft"; this.chkRightToLeft.Size = new System.Drawing.Size(120, 24); this.chkRightToLeft.TabIndex = 6; this.chkRightToLeft.Text = "RightToLeft"; // // chkCompiled // this.chkCompiled.Location = new System.Drawing.Point(16, 40); this.chkCompiled.Name = "chkCompiled"; this.chkCompiled.TabIndex = 5; this.chkCompiled.Text = "Compiled "; // // chkSingleline // this.chkSingleline.Location = new System.Drawing.Point(400, 16); this.chkSingleline.Name = "chkSingleline"; this.chkSingleline.Size = new System.Drawing.Size(120, 24); this.chkSingleline.TabIndex = 3; this.chkSingleline.Text = "Singleline"; // // chkMultiline // this.chkMultiline.Location = new System.Drawing.Point(272, 16); this.chkMultiline.Name = "chkMultiline"; this.chkMultiline.Size = new System.Drawing.Size(120, 24); this.chkMultiline.TabIndex = 2; this.chkMultiline.Text = "Multiline"; // // chkExplicitCapture // this.chkExplicitCapture.Location = new System.Drawing.Point(144, 16); this.chkExplicitCapture.Name = "chkExplicitCapture"; this.chkExplicitCapture.Size = new System.Drawing.Size(120, 24); this.chkExplicitCapture.TabIndex = 1; this.chkExplicitCapture.Text = "ExplicitCapture"; // // chkECMAScript // this.chkECMAScript.Location = new System.Drawing.Point(528, 16); this.chkECMAScript.Name = "chkECMAScript"; this.chkECMAScript.Size = new System.Drawing.Size(88, 24); this.chkECMAScript.TabIndex = 4; this.chkECMAScript.Text = "ECMAScript"; // // chkIgnoreCase // this.chkIgnoreCase.Checked = true; this.chkIgnoreCase.CheckState = System.Windows.Forms.CheckState.Checked; this.chkIgnoreCase.Location = new System.Drawing.Point(16, 16); this.chkIgnoreCase.Name = "chkIgnoreCase"; this.chkIgnoreCase.Size = new System.Drawing.Size(120, 24); this.chkIgnoreCase.TabIndex = 0; this.chkIgnoreCase.Text = "IgnoreCase"; // // pnlTest // this.pnlTest.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pnlTest.Controls.Add(this.btnOpenInput); this.pnlTest.Controls.Add(this.label6); this.pnlTest.Controls.Add(this.txtTest); this.pnlTest.Location = new System.Drawing.Point(8, 161); this.pnlTest.Name = "pnlTest"; this.pnlTest.Size = new System.Drawing.Size(672, 247); this.pnlTest.TabIndex = 9; // // btnOpenInput // this.btnOpenInput.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnOpenInput.Location = new System.Drawing.Point(553, 4); this.btnOpenInput.Name = "btnOpenInput"; this.btnOpenInput.Size = new System.Drawing.Size(96, 23); this.btnOpenInput.TabIndex = 9; this.btnOpenInput.Text = "从文件导入(&F)"; this.btnOpenInput.Click += new System.EventHandler(this.btnOpenInput_Click); // // label6 // this.label6.Location = new System.Drawing.Point(8, 8); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(80, 16); this.label6.TabIndex = 7; this.label6.Text = "测试字符串"; // // txtTest // this.txtTest.Dock = System.Windows.Forms.DockStyle.Bottom; this.txtTest.Location = new System.Drawing.Point(0, 31); this.txtTest.Multiline = true; this.txtTest.Name = "txtTest"; this.txtTest.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txtTest.Size = new System.Drawing.Size(672, 216); this.txtTest.TabIndex = 8; this.txtTest.Text = ""; // // pnlResultTv // this.pnlResultTv.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pnlResultTv.Controls.Add(this.btnExpand); this.pnlResultTv.Controls.Add(this.label1); this.pnlResultTv.Controls.Add(this.tvMatch); this.pnlResultTv.Location = new System.Drawing.Point(8, 472); this.pnlResultTv.Name = "pnlResultTv"; this.pnlResultTv.Size = new System.Drawing.Size(672, 168); this.pnlResultTv.TabIndex = 9; // // btnExpand // this.btnExpand.Location = new System.Drawing.Point(552, 0); this.btnExpand.Name = "btnExpand"; this.btnExpand.Size = new System.Drawing.Size(112, 23); this.btnExpand.TabIndex = 11; this.btnExpand.Text = "展开所有内容(&E)"; this.btnExpand.Click += new System.EventHandler(this.btnExpand_Click); // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(56, 16); this.label1.TabIndex = 10; this.label1.Text = "匹配结果"; // // tvMatch // this.tvMatch.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tvMatch.ImageIndex = -1; this.tvMatch.Location = new System.Drawing.Point(0, 24); this.tvMatch.Name = "tvMatch"; this.tvMatch.SelectedImageIndex = -1; this.tvMatch.Size = new System.Drawing.Size(672, 144); this.tvMatch.TabIndex = 9; // // btnMatch // this.btnMatch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnMatch.Location = new System.Drawing.Point(337, 648); this.btnMatch.Name = "btnMatch"; this.btnMatch.TabIndex = 10; this.btnMatch.Text = "Match(&M)"; this.btnMatch.Click += new System.EventHandler(this.btnMatch_Click); // // btnSplit // this.btnSplit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnSplit.Location = new System.Drawing.Point(433, 648); this.btnSplit.Name = "btnSplit"; this.btnSplit.TabIndex = 11; this.btnSplit.Text = "Split(&S)"; this.btnSplit.Click += new System.EventHandler(this.btnSplit_Click); // // btnReplace // this.btnReplace.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnReplace.Location = new System.Drawing.Point(521, 648); this.btnReplace.Name = "btnReplace"; this.btnReplace.TabIndex = 12; this.btnReplace.Text = "Replace(&R)"; this.btnReplace.Click += new System.EventHandler(this.btnReplace_Click); // // btnMatches // this.btnMatches.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnMatches.Location = new System.Drawing.Point(608, 648); this.btnMatches.Name = "btnMatches"; this.btnMatches.TabIndex = 13; this.btnMatches.Text = "Matches(&A)"; this.btnMatches.Click += new System.EventHandler(this.btnMatches_Click); // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.txtReplacement); this.groupBox1.Location = new System.Drawing.Point(8, 416); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(672, 56); this.groupBox1.TabIndex = 14; this.groupBox1.TabStop = false; this.groupBox1.Text = "替换字符串"; // // txtReplacement // this.txtReplacement.Dock = System.Windows.Forms.DockStyle.Fill; this.txtReplacement.Location = new System.Drawing.Point(3, 17); this.txtReplacement.Multiline = true; this.txtReplacement.Name = "txtReplacement"; this.txtReplacement.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txtReplacement.Size = new System.Drawing.Size(666, 36); this.txtReplacement.TabIndex = 9; this.txtReplacement.Text = ""; // // pnlResultTxt // this.pnlResultTxt.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pnlResultTxt.Controls.Add(this.btnSaveResult); this.pnlResultTxt.Controls.Add(this.txtResult); this.pnlResultTxt.Controls.Add(this.label2); this.pnlResultTxt.Location = new System.Drawing.Point(8, 472); this.pnlResultTxt.Name = "pnlResultTxt"; this.pnlResultTxt.Size = new System.Drawing.Size(672, 168); this.pnlResultTxt.TabIndex = 15; // // btnSaveResult // this.btnSaveResult.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnSaveResult.Location = new System.Drawing.Point(560, 0); this.btnSaveResult.Name = "btnSaveResult"; this.btnSaveResult.Size = new System.Drawing.Size(88, 23); this.btnSaveResult.TabIndex = 12; this.btnSaveResult.Text = "保存匹配结果"; this.btnSaveResult.Click += new System.EventHandler(this.btnSaveResult_Click); // // txtResult // this.txtResult.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtResult.Location = new System.Drawing.Point(0, 24); this.txtResult.Multiline = true; this.txtResult.Name = "txtResult"; this.txtResult.ReadOnly = true; this.txtResult.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txtResult.Size = new System.Drawing.Size(672, 144); this.txtResult.TabIndex = 11; this.txtResult.Text = ""; // // label2 // this.label2.Location = new System.Drawing.Point(8, 8); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(56, 16); this.label2.TabIndex = 10; this.label2.Text = "匹配结果"; // // frmRegexTester // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(688, 677); this.Controls.Add(this.pnlResultTxt); this.Controls.Add(this.groupBox1); this.Controls.Add(this.btnMatches); this.Controls.Add(this.btnReplace); this.Controls.Add(this.btnSplit); this.Controls.Add(this.btnMatch); this.Controls.Add(this.pnlTest); this.Controls.Add(this.grpRegOption); this.Controls.Add(this.btnSavePtn); this.Controls.Add(this.btnOpenPtn); this.Controls.Add(this.label5); this.Controls.Add(this.btnIsMatch); this.Controls.Add(this.txtPattern); this.Controls.Add(this.pnlResultTv); this.MinimumSize = new System.Drawing.Size(650, 600); this.Name = "frmRegexTester"; this.Text = "正则表达式测试器"; this.grpRegOption.ResumeLayout(false); this.pnlTest.ResumeLayout(false); this.pnlResultTv.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.pnlResultTxt.ResumeLayout(false); this.ResumeLayout(false); } #endregion ////// 应用程序的主入口点。 /// [STAThread] static void Main() { Application.Run(new frmRegexTester()); } #region 自定义函数 //从指定文件中得到匹配字符串 private void btnOpenPtn_Click(object sender, System.EventArgs e) { try{ if(dlgOpen.ShowDialog() == DialogResult.OK ){ txtPattern.Text= RegexTest.GetContent(dlgOpen.FileName); } }catch( Exception ex){ MessageBox.Show(ex.Message,"文件操作错误"); } } //把匹配模式保存到文件中,使用append方式 private void btnSavePtn_Click(object sender, System.EventArgs e) { try{ if( dlgSave.ShowDialog() == DialogResult.OK){ RegexTest.SaveContent(dlgSave.FileName,txtPattern.Text); } }catch( Exception ex){ MessageBox.Show(ex.Message,"错误"); } } //保存匹配结果 private void btnSaveResult_Click(object sender, System.EventArgs e) { if( txtResult.Text ==""){ MessageBox.Show("匹配结果内容为空\n不能保存","错误"); return; } } //从指定文件中得到要匹配的内容 private void btnOpenInput_Click(object sender, System.EventArgs e) { try{ if(dlgOpen.ShowDialog() == DialogResult.OK ){ txtTest.Text= RegexTest.GetContent(dlgOpen.FileName); } }catch( Exception ex){ MessageBox.Show(ex.Message,"文件操作错误"); } } //扩展所有的TreeView控件内容 private void btnExpand_Click(object sender, System.EventArgs e) { this.tvMatch.ExpandAll(); } //得到指定的RegexOptions选项 private RegexOptions GetRegexOptions(){ RegexOptions regOpt = RegexOptions.None; if( chkCompiled.Checked == true) regOpt |= RegexOptions.Compiled; if( chkCultureInvariant.Checked == true) regOpt |= RegexOptions.CultureInvariant; if( chkECMAScript.Checked == true) regOpt |= RegexOptions.ECMAScript; if( chkExplicitCapture.Checked == true) regOpt |= RegexOptions.ExplicitCapture; if( chkIgnoreCase.Checked == true) regOpt |= RegexOptions.IgnoreCase; if( chkIgnorePatternWhitespace.Checked==true) regOpt |= RegexOptions.IgnorePatternWhitespace; if( chkMultiline.Checked == true) regOpt |= RegexOptions.Multiline; if( chkRightToLeft.Checked == true) regOpt |= RegexOptions.RightToLeft; if( chkSingleline.Checked == true) regOpt |= RegexOptions.Singleline; return regOpt; } //是否匹配 private void btnIsMatch_Click(object sender, System.EventArgs e) { if( RegexTest.IsMatch(txtPattern.Text,txtTest.Text,this.GetRegexOptions())){ MessageBox.Show("匹配成功!","匹配成功"); }else{ MessageBox.Show("匹配不成功\n你也许需要修改Pattern","匹配不成功"); } } //只进行一次匹配测试 private void btnMatch_Click(object sender, System.EventArgs e) { pnlResultTxt.Visible= false; pnlResultTv.Visible = true; this.tvMatch.Nodes.Clear(); RegexTest regTest = new RegexTest(this.GetRegexOptions()); regTest.Pattern = txtPattern.Text; regTest.Input = txtTest.Text; regTest.Match(this.tvMatch); } //字符串分割 private void btnSplit_Click(object sender, System.EventArgs e) { pnlResultTv.Visible = false; pnlResultTxt.Visible = true; txtResult.Text = ""; RegexTest regTest = new RegexTest(this.GetRegexOptions()); regTest.Pattern = txtPattern.Text; regTest.Input = txtTest.Text; regTest.Split(txtResult); } //字符串替换 private void btnReplace_Click(object sender, System.EventArgs e) { pnlResultTv.Visible = false; pnlResultTxt.Visible = true; txtResult.Text = ""; RegexTest regTest = new RegexTest(this.GetRegexOptions()); regTest.Pattern = txtPattern.Text; regTest.Input = txtTest.Text; regTest.Replace(txtResult,txtReplacement.Text); } //得到所有匹配组 private void btnMatches_Click(object sender, System.EventArgs e) { pnlResultTxt.Visible= false; pnlResultTv.Visible = true; this.tvMatch.Nodes.Clear(); RegexTest regTest = new RegexTest(this.GetRegexOptions()); regTest.Pattern = txtPattern.Text; regTest.Input = txtTest.Text; regTest.Matches(this.tvMatch); } #endregion } } RegexTest类代码: /* 程序名 : RegexTester * 用途 : .net下的正则表达式测试程序 * 文件名 : RegexTest.cs * 作者 : silverduck * 日期 : 04/05/2004 * e-Mail : [email protected] */ using System; using System.IO; using System.Windows.Forms; using System.Text.RegularExpressions; namespace RegexTester { ////// 正则表达式测试类。用于测试各种正则表达式。 /// public class RegexTest { #region 私有变量 private string pattern; //模式字符串 private string input; //输入字符串 private Regex rgx; //正则表带式 private RegexOptions rgxOpt; //正则表达式选项 #endregion 私有变量 #region 公有属性 ////// 匹配模式字符串 /// public string Pattern{ get{ return pattern;} set{ pattern = value;} } ////// 输入的要匹配的字符串 /// public string Input{ get{ return input;} set{ input = value;} } ////// 正则表达式选项 /// public RegexOptions RgxOptions{ get{return rgxOpt;} set{rgxOpt = value;} } #endregion 公有属性 #region 构造函数 ////// 正则表达式测试类构造函数 /// ///正则表达式选项 public RegexTest(RegexOptions rgxOpt):this(rgxOpt,"",""){ } ////// 正则表达式测试类构造函数 /// ///正则表达式选项 ///模式匹配字符串 ///输入字符串 public RegexTest(RegexOptions rgxOpt,string pattern,string input){ this.Pattern = pattern; this.rgxOpt = rgxOpt; this.Input = input; rgx = null; } #endregion 构造函数 #region 私有方法 ////// 得到正则表达式类 /// private void CreateRegex(){ if( pattern != "" && input != ""){ rgx = new Regex(pattern,rgxOpt); } } ////// 设置显示匹配结果的TreeView控件 /// /// 显示匹配结果的TreeView控件 /* 在TreeView控件中显示的内容格式: ╠匹配成功 ╚Match数目 ╠Match-0 ╠结果 ╠Group数目 ╠Match属性index ╠Match属性length ╠Match属性value ╠Group-0 ╠结果 ╠Capture数目 ╠Group属性index ╠Group属性length ╠Group属性value ╠Capture-0 ╠Capture属性index ╠Capture属性length ╠... ╠Capture-1 ╠Capture属性 ╠Capture属性 ╠... ╠... ╠Capture-n ╠Group-1 ╠结果 ╠... ╠Capture-0 ╠Capture属性 ╠Capture属性 ╠... ╠... ╠Capture-n ╠... ╠Group-n ╠Match-1 ╠结果 ╠... ╠Group-0 ... ╠Group-n ... ╠Match-n */ private void SetShowResultTreeView(MatchCollection aMatch,TreeView tvShowResult){ //指定的TreeView控件不为空则向其中写入值 //否则不作任何处理 if( tvShowResult != null && aMatch != null ){ tvShowResult.BeginUpdate(); tvShowResult.Nodes.Clear(); //写入捕获结果总体信息 if( aMatch.Count > 0){ tvShowResult.Nodes.Add("匹配成功"); tvShowResult.Nodes[0].Nodes.Add("Match数—"+aMatch.Count.ToString()); for( int i=0;i < aMatch.Count && aMatch[i].Success;i++ ){ TreeNode tn = new TreeNode("Match - " + i.ToString()); this.AddMatch(tn,aMatch[i]); tvShowResult.Nodes.Add(tn); } } //写入各个捕获组 tvShowResult.EndUpdate(); } } ////// 向TreeNode中插入匹配所得的Match /// /// 要向其中插入内容的节点 /// 要插入到节点中的Match结果 private void AddMatch(TreeNode tn, Match mth){ tn.Nodes.Add("结果"); tn.Nodes[0].Nodes.Add("Group 数 — "+mth.Captures.Count.ToString()); tn.Nodes[0].Nodes.Add("起始位置 — "+mth.Index.ToString()); tn.Nodes[0].Nodes.Add("长 度 — "+mth.Length.ToString()); tn.Nodes[0].Nodes.Add("捕 获 值 — "+mth.Value); for( int i=0;i < mth.Groups.Count;i++ ){ TreeNode tnd = new TreeNode("Group - " + i.ToString()); this.AddGroup(tnd,mth.Groups[i]); tn.Nodes.Add(tnd); } } ////// 向TreeNode中插入匹配所得的Group /// /// 要向其中插入内容的节点 /// 要插入到节点中的Group结果 private void AddGroup(TreeNode tn, Group grp){ tn.Nodes.Add("结果"); tn.Nodes[0].Nodes.Add("Capture数—"+grp.Captures.Count.ToString()); tn.Nodes[0].Nodes.Add("起始位置 — "+grp.Index.ToString()); tn.Nodes[0].Nodes.Add("长 度 — "+grp.Length.ToString()); tn.Nodes[0].Nodes.Add("捕 获 值 — "+grp.Value); for( int i=0;i < grp.Captures.Count;i++ ){ TreeNode tnd = new TreeNode("Capture - " + i.ToString()); this.AddCapture(tnd,grp.Captures[i]); tn.Nodes.Add(tnd); } } ////// 向TreeNode中插入匹配所得的Capture /// /// 要向其中插入内容的节点 /// 要插入到节点中的Capture结果 private void AddCapture(TreeNode tn, Capture cpt){ tn.Nodes.Add("起始位置 — "+cpt.Index.ToString()); tn.Nodes.Add("长 度 — "+cpt.Length.ToString()); tn.Nodes.Add("捕 获 值 — "+cpt.Value); } #endregion 私有方法 #region 公有方法 ////// 根据给定的匹配模式替换输入的字符串 /// public void Matches(TreeView tv){ MatchCollection aMatch; this.CreateRegex(); if( rgx != null){ aMatch=rgx.Matches(input); this.SetShowResultTreeView(aMatch,tv); } } ////// 得到一次匹配结果 /// /// 显示匹配结果的TreeView控件 public void Match(TreeView tv){ this.CreateRegex(); if( rgx != null){ Match mth = rgx.Match(input); if( mth.Success){ TreeNode tn= new TreeNode("匹配成功"); tv.Nodes.Add(tn); this.AddMatch(tn,mth); } } } ////// 根据给定的匹配模式分隔输入的字符串 /// /// 要在其中显示结果的文本框控件 public void Split(TextBox txtResult){ this.CreateRegex(); if( rgx != null){ string[] aStr = rgx.Split(input); txtResult.AppendText("通过分割共得到"+aStr.Length.ToString()+"个字符串。它们分别为:"+System.Environment.NewLine); foreach( string s in aStr){ txtResult.AppendText(s+System.Environment.NewLine); } } } ////// 根据给定的匹配模式替换输入的字符串 /// /// 要在其中显示结果的文本框控件 /// 替换的内容 public void Replace(TextBox txtResult,string replacement){ this.CreateRegex(); if( rgx != null){ txtResult.AppendText( "替换结果为:"+ System.Environment.NewLine); txtResult.AppendText(rgx.Replace(input,replacement)); } } ////// 是否匹配指定内容 /// public static bool IsMatch(string pattern,string content,RegexOptions regOpt){ return Regex.IsMatch(content,pattern,regOpt); } ////// 从指定的文件中得到字符串 /// /// 要从中得到字符串的文件名 ///返回从文件中得到的字符串 public static string GetContent(string fileName){ string content=""; try{ StreamReader sr = new StreamReader(fileName,System.Text.Encoding.Default,true); content = sr.ReadToEnd(); sr.Close(); }catch(Exception ex){ throw ex; } return content; } ////// 把指定的内容存入到指定的文件名中 /// /// 要存入内容的文件名 /// 要存入的内容 public static void SaveContent(string fileName,string content){ try{ StreamWriter sw = new StreamWriter(fileName,true,System.Text.Encoding.Default); sw.Write(content+System.Environment.NewLine); sw.Close(); }catch(Exception ex){ throw ex; } } #endregion } }
本文地址:http://com.8s8s.com/it/it44952.htm