CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Regex Sampler

329 Views
Copy Code Show/Hide Line Numbers
   1:  using System;
   2:  using System.Drawing;
   3:  using System.Collections;
   4:  using System.ComponentModel;
   5:  using System.Windows.Forms;
   6:  using System.Data;
   7:  using System.Text.RegularExpressions;
   8:  using System.Text;
   9:  using System.IO;
  10:  using System.Reflection;
  11:   
  12:  namespace Regex_Sample
  13:  {
  14:      /// <summary>
  15:      /// Summary description for Form1.
  16:      /// </summary>
  17:      public class Form1 : System.Windows.Forms.Form
  18:      {
  19:          internal System.Windows.Forms.Label lblResult;
  20:          internal System.Windows.Forms.Button btnValidatePhone;
  21:        internal System.Windows.Forms.Label lblSelectedTarget;
  22:        internal System.Windows.Forms.Label lblSelectedExpression;
  23:        internal System.Windows.Forms.ComboBox comboTarget;
  24:        internal System.Windows.Forms.ComboBox comboExpression;
  25:        internal System.Windows.Forms.TextBox txtResult;
  26:        internal System.Windows.Forms.Button btnFindAMatch;
  27:        internal System.Windows.Forms.TextBox txtTarget;
  28:        internal System.Windows.Forms.Label lblTarget;
  29:        internal TextBox txtRegex;
  30:        internal Label lblRegex;
  31:          /// <summary>
  32:          /// Required designer variable.
  33:          /// </summary>
  34:          private System.ComponentModel.Container components = null;
  35:   
  36:          public Form1()
  37:          {
  38:              //
  39:              // Required for Windows Form Designer support
  40:              //
  41:              InitializeComponent();
  42:   
  43:              //
  44:              // TODO: Add any constructor code after InitializeComponent call
  45:              //
  46:          }
  47:   
  48:          /// <summary>
  49:          /// Clean up any resources being used.
  50:          /// </summary>
  51:          protected override void Dispose( bool disposing )
  52:          {
  53:              if( disposing )
  54:              {
  55:                  if (components != null) 
  56:                  {
  57:                      components.Dispose();
  58:                  }
  59:              }
  60:              base.Dispose( disposing );
  61:          }
  62:   
  63:          #region Windows Form Designer generated code
  64:          /// <summary>
  65:          /// Required method for Designer support - do not modify
  66:          /// the contents of this method with the code editor.
  67:          /// </summary>
  68:          private void InitializeComponent()
  69:          {
  70:              this.lblResult = new System.Windows.Forms.Label();
  71:              this.btnValidatePhone = new System.Windows.Forms.Button();
  72:              this.lblSelectedTarget = new System.Windows.Forms.Label();
  73:              this.lblSelectedExpression = new System.Windows.Forms.Label();
  74:              this.comboTarget = new System.Windows.Forms.ComboBox();
  75:              this.comboExpression = new System.Windows.Forms.ComboBox();
  76:              this.txtResult = new System.Windows.Forms.TextBox();
  77:              this.btnFindAMatch = new System.Windows.Forms.Button();
  78:              this.txtTarget = new System.Windows.Forms.TextBox();
  79:              this.lblTarget = new System.Windows.Forms.Label();
  80:              this.txtRegex = new System.Windows.Forms.TextBox();
  81:              this.lblRegex = new System.Windows.Forms.Label();
  82:              this.SuspendLayout();
  83:              // 
  84:              // lblResult
  85:              // 
  86:              this.lblResult.Location = new System.Drawing.Point(32, 331);
  87:              this.lblResult.Name = "lblResult";
  88:              this.lblResult.Size = new System.Drawing.Size(168, 16);
  89:              this.lblResult.TabIndex = 25;
  90:              this.lblResult.Text = "Result";
  91:              // 
  92:              // btnValidatePhone
  93:              // 
  94:              this.btnValidatePhone.Location = new System.Drawing.Point(592, 109);
  95:              this.btnValidatePhone.Name = "btnValidatePhone";
  96:              this.btnValidatePhone.Size = new System.Drawing.Size(168, 23);
  97:              this.btnValidatePhone.TabIndex = 23;
  98:              this.btnValidatePhone.Text = "Validate Phone Number";
  99:              this.btnValidatePhone.Click += new System.EventHandler(this.btnValidatePhone_Click);
 100:              // 
 101:              // lblSelectedTarget
 102:              // 
 103:              this.lblSelectedTarget.Location = new System.Drawing.Point(32, 57);
 104:              this.lblSelectedTarget.Name = "lblSelectedTarget";
 105:              this.lblSelectedTarget.Size = new System.Drawing.Size(160, 15);
 106:              this.lblSelectedTarget.TabIndex = 20;
 107:              this.lblSelectedTarget.Text = "Selected Target:";
 108:              // 
 109:              // lblSelectedExpression
 110:              // 
 111:              this.lblSelectedExpression.Location = new System.Drawing.Point(32, 16);
 112:              this.lblSelectedExpression.Name = "lblSelectedExpression";
 113:              this.lblSelectedExpression.Size = new System.Drawing.Size(184, 15);
 114:              this.lblSelectedExpression.TabIndex = 19;
 115:              this.lblSelectedExpression.Text = "Selected Expression:";
 116:              // 
 117:              // comboTarget
 118:              // 
 119:              this.comboTarget.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
 120:              this.comboTarget.Location = new System.Drawing.Point(32, 73);
 121:              this.comboTarget.Name = "comboTarget";
 122:              this.comboTarget.Size = new System.Drawing.Size(728, 21);
 123:              this.comboTarget.TabIndex = 18;
 124:              this.comboTarget.SelectedIndexChanged += new System.EventHandler(this.comboTarget_SelectedIndexChanged);
 125:              // 
 126:              // comboExpression
 127:              // 
 128:              this.comboExpression.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
 129:              this.comboExpression.Location = new System.Drawing.Point(32, 32);
 130:              this.comboExpression.Name = "comboExpression";
 131:              this.comboExpression.Size = new System.Drawing.Size(728, 21);
 132:              this.comboExpression.TabIndex = 17;
 133:              this.comboExpression.SelectedIndexChanged += new System.EventHandler(this.comboExpression_SelectedIndexChanged);
 134:              // 
 135:              // txtResult
 136:              // 
 137:              this.txtResult.Dock = System.Windows.Forms.DockStyle.Bottom;
 138:              this.txtResult.Font = new System.Drawing.Font("Courier New", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
 139:              this.txtResult.Location = new System.Drawing.Point(0, 362);
 140:              this.txtResult.Multiline = true;
 141:              this.txtResult.Name = "txtResult";
 142:              this.txtResult.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
 143:              this.txtResult.Size = new System.Drawing.Size(792, 386);
 144:              this.txtResult.TabIndex = 16;
 145:              // 
 146:              // btnFindAMatch
 147:              // 
 148:              this.btnFindAMatch.Location = new System.Drawing.Point(32, 109);
 149:              this.btnFindAMatch.Name = "btnFindAMatch";
 150:              this.btnFindAMatch.Size = new System.Drawing.Size(168, 23);
 151:              this.btnFindAMatch.TabIndex = 15;
 152:              this.btnFindAMatch.Text = "Find A Match";
 153:              this.btnFindAMatch.Click += new System.EventHandler(this.btnFindAMatch_Click);
 154:              // 
 155:              // txtTarget
 156:              // 
 157:              this.txtTarget.Font = new System.Drawing.Font("Courier New", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
 158:              this.txtTarget.Location = new System.Drawing.Point(0, 251);
 159:              this.txtTarget.Multiline = true;
 160:              this.txtTarget.Name = "txtTarget";
 161:              this.txtTarget.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
 162:              this.txtTarget.Size = new System.Drawing.Size(792, 68);
 163:              this.txtTarget.TabIndex = 26;
 164:              // 
 165:              // lblTarget
 166:              // 
 167:              this.lblTarget.Location = new System.Drawing.Point(29, 232);
 168:              this.lblTarget.Name = "lblTarget";
 169:              this.lblTarget.Size = new System.Drawing.Size(168, 16);
 170:              this.lblTarget.TabIndex = 27;
 171:              this.lblTarget.Text = "Target";
 172:              // 
 173:              // txtRegex
 174:              // 
 175:              this.txtRegex.Font = new System.Drawing.Font("Courier New", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
 176:              this.txtRegex.Location = new System.Drawing.Point(0, 166);
 177:              this.txtRegex.Multiline = true;
 178:              this.txtRegex.Name = "txtRegex";
 179:              this.txtRegex.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
 180:              this.txtRegex.Size = new System.Drawing.Size(792, 54);
 181:              this.txtRegex.TabIndex = 28;
 182:              // 
 183:              // lblRegex
 184:              // 
 185:              this.lblRegex.Location = new System.Drawing.Point(29, 147);
 186:              this.lblRegex.Name = "lblRegex";
 187:              this.lblRegex.Size = new System.Drawing.Size(168, 16);
 188:              this.lblRegex.TabIndex = 29;
 189:              this.lblRegex.Text = "Regular Expression";
 190:              // 
 191:              // Form1
 192:              // 
 193:              this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
 194:              this.ClientSize = new System.Drawing.Size(792, 748);
 195:              this.Controls.Add(this.lblRegex);
 196:              this.Controls.Add(this.txtRegex);
 197:              this.Controls.Add(this.lblTarget);
 198:              this.Controls.Add(this.txtTarget);
 199:              this.Controls.Add(this.lblResult);
 200:              this.Controls.Add(this.btnValidatePhone);
 201:              this.Controls.Add(this.lblSelectedTarget);
 202:              this.Controls.Add(this.lblSelectedExpression);
 203:              this.Controls.Add(this.comboTarget);
 204:              this.Controls.Add(this.comboExpression);
 205:              this.Controls.Add(this.txtResult);
 206:              this.Controls.Add(this.btnFindAMatch);
 207:              this.Name = "Form1";
 208:              this.Text = "Regex Sampler";
 209:              this.Load += new System.EventHandler(this.Form1_Load);
 210:              this.ResumeLayout(false);
 211:              this.PerformLayout();
 212:   
 213:        }
 214:          #endregion
 215:   
 216:          /// <summary>
 217:          /// The main entry point for the application.
 218:          /// </summary>
 219:          [STAThread]
 220:          static void Main() 
 221:          {
 222:              Application.Run(new Form1());
 223:          }
 224:   
 225:        private void Form1_Load(object sender, System.EventArgs e)
 226:        {
 227:            this.comboExpression.Items.Add(@"simple dates ::\d{1,2}/\d{1,2}");
 228:            this.comboExpression.Items.Add(@"dates 1 ::\d{1,2}/((\d{4})|(\d{1,2}))");
 229:            this.comboExpression.Items.Add(@"dates 2 ::\d{1,2}/\d{1,4}");
 230:            this.comboExpression.Items.Add(@"dates 3 ::\d{1,2}/(\d{1,2}|\d{4})");
 231:            this.comboExpression.Items.Add(@"dates 4 ::\d{1,2}/(\d{4}|\d{1,2})");
 232:            this.comboExpression.Items.Add(@"dates 5 ::\s\d{1,2}/(\d{4}|\d{1,2})");
 233:            this.comboExpression.Items.Add(@"dates 6 ::\s*\d{1,2}/(\d{4}|\d{1,2})");
 234:            this.comboExpression.Items.Add(@"dates 7 ::\s*\d{1,2}/(\d{4}|\d{1,2})(\s|\W)");
 235:            this.comboExpression.Items.Add(@"dates 8 ::(\b|\s*)\d{1,2}/(\d{4}|\d{1,2})(\s|\W|\b)");
 236:            this.comboExpression.Items.Add(@"advanced date matching  ::(\b|\s*)\d{1,2}/(\d{4}|\d{1,2})(\s|(\W|[^/\d])|\b)");
 237:            this.comboExpression.Items.Add(@"more advanced date matching ::(\b|\s*)\d{1,2}/(\d{4}|\d{1,2})(/(\d{4}|\d{1,2}))?((\s|(\W[^/\d]))|\b){1}");
 238:            this.comboExpression.Items.Add(@"matches dates with named grouping ::(\b|\s*)(?<date>\d{1,2}/(\d{4}|\d{1,2})(/(\d{4}|\d{1,2}))?)((\s|(\W[^/\d]))|\b)");
 239:   
 240:            this.comboExpression.Items.Add(@"This is not a regular expression ::");
 241:          
 242:            // Grabbing HTML Tags
 243:            this.comboExpression.Items.Add(@"matches HTML Tags :: <([A-Za-z][A-Za-z0-9]*)\b[^>]*>(.*?)</\1>");
 244:   
 245:            // Finding comments
 246:            
 247:            // matches a single-line comment starting with a # and continuing until the end of the line
 248:            this.comboExpression.Items.Add(@"matches a single-line # comment :: #.*$");
 249:   
 250:            // similar match but with // comments
 251:            this.comboExpression.Items.Add(@"matches a single-line // comment :: //.*$");
 252:   
 253:            // allows whitespace between start of line and the comment. 
 254:            this.comboExpression.Items.Add(@"allows whitespace between start of line and the # comment :: ^\s*#.*$");
 255:   
 256:            // C-style multi-line comment if you turn on the option for the dot to match newlines
 257:            this.comboExpression.Items.Add(@"C-style multi-line comment :: /\*.*?\*/"); 
 258:   
 259:            // Numbers
 260:   
 261:            // matches a positive integer number
 262:            this.comboExpression.Items.Add(@"matches a positive integer number :: \b\d+\b"); 
 263:   
 264:            // matches a positive and negative integer number
 265:            this.comboExpression.Items.Add(@"matches a positive and negative integer number :: [-+]?\b\d+\b");
 266:   
 267:            // matches a C-style hexadecimal number
 268:            this.comboExpression.Items.Add(@"matches a C-style hexadecimal number :: \b0[xX][0-9a-fA-F]+\b");
 269:   
 270:            // Email Addresses
 271:   
 272:            // this works for 99% of the cases.
 273:            this.comboExpression.Items.Add(@"matches email addresses (99% accuracy) :: \b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b");
 274:   
 275:            // There is an official standard known as RFC 2822, but  it's hardly fool-proof. 
 276:            this.comboExpression.Items.Add(@"matches email addresses (RFC 2822) :: [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|ne t|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b");
 277:   
 278:            // Dates
 279:            // matches a date in yyyy-mm-dd format from between 1900-01-01 and 2099-12-31, 
 280:            // with a choice of four separators ('-',' ','/','.')
 281:            // requires the delimiters to be consistent; will match 1999-01-01 but not 1999/01-01
 282:   
 283:            this.comboExpression.Items.Add(@"matches a date in yyyy-mm-dd format from between 1900-01-01 and 2099-12-31 :: (19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])");
 284:   
 285:            // match a date in mm/dd/yyyy format
 286:            this.comboExpression.Items.Add(@"match a date in mm/dd/yyyy format :: (0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d");
 287:   
 288:            // matches phone numbers
 289:            this.comboExpression.Items.Add(@"matches phone numbers :: (\s|\W)*1?(\s|\W)*(?<areacode>[2-9][\d]{2})(\s|\W)*(?<prefix>[\d]{3})(\s|\W)*(?<linenumber>[\d]{4})([^\d]|\b){1}");
 290:   
 291:            this.comboExpression.SelectedIndex = 0;
 292:   
 293:            this.comboTarget.Items.Add(@"Are these dates? /9/6/03, 08/05/03, 07/04/2003, 3/2003, 6/6, 02/04,        98/105 12/17/1770/03/26/1827");
 294:            this.comboTarget.Items.Add(@"Perhaps these -dates- (07/04/1776, 7-4-1776, 5.21.2009) are more to your liking.");
 295:            this.comboTarget.Items.Add(@"My phone number is 18003334444 or 1-800-123-4567 or 800-555-1111 or (800)333-7777 or 18007775555 or 1 800.555.4444 or 1(800)222-3333");
 296:            this.comboTarget.Items.Add(@"This is an IP address 192.168.0.1 that you may use frequently.");
 297:            this.comboTarget.Items.Add(@"Here are some numbers: 192 +1234 3.141 -32 98.6 -12.1 0x0ff ");
 298:            this.comboTarget.Items.Add(@"#### This would be a shell script comment. ####");
 299:            this.comboTarget.Items.Add(@"// This would be a C# comment. // But what about this one?");
 300:            this.comboTarget.Items.Add(@"This is HTML <--> <table><tr>Row 1<td>Cell 1</td></tr></table>");
 301:            this.comboTarget.Items.Add(@"You can email me at johndoe@publicindustries.com (which is just an alias for jqpublic@schmoe.com). Or email me at joe@aol.com but I check that less often.");
 302:   
 303:            this.comboTarget.SelectedIndex = 0;
 304:        }
 305:   
 306:        private void btnFindAMatch_Click(object sender, System.EventArgs e)
 307:        {
 308:            showResult((string)txtRegex.Text, (string)txtTarget.Text);
 309:        }
 310:   
 311:        private void comboExpression_SelectedIndexChanged(object sender, System.EventArgs e)
 312:        {
 313:           if (comboExpression.SelectedIndex >= 0) 
 314:           {
 315:               Regex rgx = new Regex(@"^.*::\s*");
 316:               string thePattern = rgx.Replace((string)comboExpression.SelectedItem, "");
 317:               this.txtRegex.Text = (string)thePattern;
 318:           }
 319:        }
 320:   
 321:        private void comboTarget_SelectedIndexChanged(object sender, System.EventArgs e)
 322:        {
 323:            if (comboTarget.SelectedIndex >= 0)
 324:            {
 325:                this.txtTarget.Text = (string)comboTarget.SelectedItem;
 326:            }
 327:        }
 328:   
 329:        private void showResult(string aPattern, string target) 
 330:        {
 331:           StringBuilder sb = new StringBuilder();
 332:           // display the result of the regular expression 
 333:           // aPattern applied to the target string
 334:           if ((aPattern == null) || (aPattern == String.Empty)) 
 335:           {
 336:               sb.Append("No input pattern was provided." + System.Environment.NewLine);
 337:               this.txtResult.Text = sb.ToString();
 338:               return; 
 339:           }
 340:   
 341:           // create a Regex object
 342:           Regex reg = new Regex(aPattern);
 343:   
 344:           //apply the pattern to the target
 345:           MatchCollection matches = reg.Matches(target);
 346:   
 347:           // display count of matches found
 348:           sb.Append("Found " + matches.Count + " matches: " + System.Environment.NewLine);
 349:   
 350:           //display each match
 351:           foreach(Match aMatch in matches) 
 352:           {
 353:              if (aMatch.Groups.Count > 0) 
 354:              {
 355:                 if (aMatch.Groups["date"].Value != "") 
 356:                 {
 357:                    sb.Append("Date: " + aMatch.Groups["date"].Value + System.Environment.NewLine);
 358:                 }
 359:                 else 
 360:                 {
 361:                     sb.Append("Matched text: \"" + aMatch.Value + "\", " );
 362:                     sb.Append(new String(' ', 
 363:                        (aMatch.Value.Length < 20) ? 20 - aMatch.Value.Length : 4)); 
 364:                     sb.Append("At position: " + aMatch.Index + System.Environment.NewLine);
 365:                 }
 366:              }
 367:              else 
 368:              {
 369:                 sb.Append(aMatch.Value);
 370:              }
 371:           }
 372:           // display final result
 373:           this.txtResult.Text = sb.ToString();
 374:        }
 375:   
 376:        private bool isValidPhone(string phone) 
 377:        {
 378:           string phoneregex = @"(\s|\W)*1?(\s|\W)*(?<areacode>[2-9][\d]{2})(\s|\W)*(?<prefix>[\d]{3})(\s|\W)*(?<linenumber>[\d]{4})([^\d]|\b){1}";
 379:   
 380:           this.txtRegex.Text = phoneregex;
 381:   
 382:            // create a new regular expression to check the phone number
 383:           Regex reg = new Regex(phoneregex);
 384:        
 385:           // get the match list
 386:           MatchCollection matches = reg.Matches(phone);
 387:           
 388:           StringBuilder sb = new StringBuilder();
 389:   
 390:           // are there any matches?
 391:           if (matches.Count == 0) 
 392:           {
 393:              this.txtResult.Text = "Not a valid phone number.";
 394:              return false;
 395:           }
 396:           else 
 397:           {
 398:              // display each match
 399:              foreach(Match aMatch in matches) 
 400:              {
 401:                 sb.Append("Matched text: \"" + aMatch.Value + "\", " + 
 402:                    new String(' ',20 - aMatch.Value.Length) + 
 403:                    "At position: " + aMatch.Index + System.Environment.NewLine);
 404:   
 405:                 if (aMatch.Groups.Count > 0) 
 406:                 {
 407:                    // show area code match
 408:                    if (aMatch.Groups["areacode"].Value != "") 
 409:                    {
 410:                       sb.Append("Area Code: " + aMatch.Groups["areacode"].Value + System.Environment.NewLine);
 411:                    }
 412:                    else 
 413:                    {
 414:                       return false;
 415:                    }
 416:                    if (aMatch.Groups["prefix"].Value != "") 
 417:                    {
 418:                       //show prefix match
 419:                       sb.Append("Prefix: " + aMatch.Groups["prefix"].Value + 
 420:                          System.Environment.NewLine);
 421:                    }
 422:                    else 
 423:                    {
 424:   
 425:                       return false;
 426:                    }
 427:   
 428:                    if (aMatch.Groups["linenumber"].Value != "") 
 429:                    {
 430:                       // show line number match
 431:                       sb.Append("Line Number: " + aMatch.Groups["linenumber"].Value + System.Environment.NewLine);
 432:                    }
 433:                    else 
 434:                    {
 435:                       return false;
 436:                    }
 437:                 }
 438:                 sb.Append(System.Environment.NewLine);
 439:              }
 440:           }
 441:   
 442:           // show final result
 443:           this.txtResult.Text = sb.ToString();
 444:           return true;
 445:        }
 446:   
 447:        private void btnValidatePhone_Click(object sender, System.EventArgs e)
 448:        {
 449:           string phone = txtTarget.Text;
 450:          
 451:           // validate the phone number
 452:           if (!isValidPhone(phone)) 
 453:           {
 454:              this.txtResult.Text = "Not a valid phone number.";
 455:              txtTarget.Focus();
 456:           }
 457:           else 
 458:           {
 459:              this.txtResult.AppendText(System.Environment.NewLine + "The phone number is valid.");
 460:           }
 461:        }
 462:    
 463:     }
 464:  }
by Dean Weber
  October 08, 2009 @ 7:54am
Tags:
Description:
This is the source code for my Regex Sampler program used in my Regular Expressions in .NET presentation.

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate