Wednesday, October 22, 2014

Regular Expressions in C#: A Beginners Guide

Introduction:

Enjoy validating data within your code?  Want an extra super peachy keen neato way of validating data that works?  Have no fear (well, some), regular expressions are here!

Pre-Code Explanation:

Creating a validation string isn't as imposing as some of the sites you might have googled prior to this tutorial.  For easing into creating your own validation string(s):

The \d tag matches any decimal digit.
The \D tag matches any non-decimal digit.
The ^ tag (carat) requires the string to match at the beginning of the compare string.
The {n} phrase matches n number of characters in a pattern.
The $ tag requires the match to occur at the end of a string.

So something like ^\\D{4}-\\d{3}$ could validate the string dude-123 and invalidate 1234-123

Code Sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpConsoleAppRegularExpression
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] zipcodeValues = {
                                  "12345-6789",
                                  "12345-67890",
                                  "1234-56789"
                              };
            string regularExpressionPattern = "^\\d{5}-\\d{4}$";
            string[] phoneNumberValues = {
                                             "555-555-1234",
                                             "55-555-12345",
                                             "555-55-12345",
                                             "555-555-234A"
                                         };
            string phoneNumberValidationPattern = "^\\d{3}-\\d{3}-\\d{4}$";

            string[] genericStringArray = {
                                              "dude-123",
                                              "1234-123"
                                          };
            string genericStringValidationPattern = "^\\D{4}-\\d{3}$";

            System.Console.WriteLine("Validation section for zipcodes:");
            foreach (string value in zipcodeValues)
            {
                System.Console.Write("{0,14}", value);
                if (System.Text.RegularExpressions.Regex.IsMatch(value, regularExpressionPattern))
                    System.Console.WriteLine(" - valid expression");
                else
                    System.Console.WriteLine(" - invalid expression");
            }
            System.Console.WriteLine("Validation section for phone numbers:");
            foreach (string value in phoneNumberValues)
            {
                System.Console.Write("{0,14}", value);
                if (System.Text.RegularExpressions.Regex.IsMatch(value, phoneNumberValidationPattern))
                    System.Console.WriteLine(" - valid expression");
                else
                    System.Console.WriteLine(" - invalid expression");
            }
            System.Console.WriteLine("Validation section for generic string array");
            foreach (string value in genericStringArray)
            {
                System.Console.Write("{0,14}", value);
                if (System.Text.RegularExpressions.Regex.IsMatch(value, genericStringValidationPattern))
                    System.Console.WriteLine(" - valid expression");
                else
                    System.Console.WriteLine(" - invalid expression");
            }

            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}

Output:















Prologue:

Regular expressions can be quite useful for validation.  Next week I'll discuss advanced techniques using regular expressions for data validation.

Source:

No comments:

Post a Comment