Tuesday, December 6, 2011

Example of Regex: validating GUID

Here is a simple example of Regex used to validate GUID.
using System;
using System.Text.RegularExpressions;

namespace Program
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            string[] uuids = new string[]
            {
                Guid.NewGuid().ToString("D"), 
                Guid.NewGuid().ToString("D"),
                "some random string"
            };
   
            foreach(string uuid in uuids)
            {
                Console.WriteLine("uuid: '{0}' macth '{1}'", 
                    uuid, Regex.IsMatch(uuid, @"^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$"));
            }
        }
    }
}