Click here to Skip to main content
12,064,498 members (55,474 online)
Click here to Skip to main content
Add your own
alternative version

Stats

13.4K views
10 bookmarked
Posted

Use a Regex to parse a GUID (and keep it unchanged at runtime)

, 15 Jun 2015 CPOL
Rate this:
Please Sign up or sign in to vote.
A short Reference on how you can validate a registry-formatted GUID with a regular expression

Introduction

I assume that you bring a bit of background knowledge on regular expressions and the .Net framework with you.

Whatsoever, I keep this one straight forward: I assume that a valid registry formatted GUID looks like that:

{A9526723-C3BC-4A36-ADF8-9AC7CBDCEE52}

As you can see it's easy:

  • Open curly brackets
  • an 8 characters digit-letter combination
  • Hyphen
  • a 4 characters digit-letter combination, repeating 3 times (each of the repeating sequences separated by a hyphen)
  • a 12 characters digit-letter combination,
  • and closing curly brackets.

Using the code

The regex itself looks pretty straightforward:

^{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}}$

I built it into the CoreResource class of the Springlog Project, a Syslog implementation on .Net which is currently under heavy development:

using System;
using System.Text.RegularExpressions;

namespace Springlog.Core
{
    internal static class CoreResources
    {
        static string customerGuid = "{A9526723-C3BC-4A36-ADF8-9AC7CBDCEE52}";
        /// <summary>
        /// GUID to identify the application which uses the Springlog.Core
        /// library.
        /// </summary>
        internal static string CustomerGuid
        {
            get { return CoreResources.customerGuid; }
            set 
            {
                Regex regex = new Regex("^{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}}$");
                Match match = regex.Match(value);
                if (match.Success)
                {
                    CoreResources.customerGuid = value; 
                }
                else
                {
                    throw new ArgumentOutOfRangeException("The submitted string is not a valid GUID. Springlog.Core.CoreResources.CustomerGuid "+
                        "needs to be formatted as registry GUID, for example \"{A9526723-C3BC-4A36-ADF8-9AC7CBDCEE52}\"");
                }
            }
        }
    }
}

You may ask yourself why I marked this class as internal, don't you? There is a facade before it in order to be able to control the outside access to the CoreResources class, called Configurator.

namespace Springlog.Core
{
    public class Configurator
    {
        public void ConfigureCore(string customerGuid)
        {
            CoreResources.CustomerGuid = customerGuid;
        }
    }
}

I admit that this construction may be confusing, but it allows me to abstract the Resources class from what the other applications sees outside. For example, if I decide to rename CustomerGuid to CustomerAppGuid it won't affect the application which uses Springlog. Apart from that it allows me to use the Configurator class as access controller and for example prevent the main application (which uses Springlog) from changing the GUID more than once a runtime:

namespace Springlog.Core
{
    public class Configurator
    {
        bool customerGuidSet = false;
        public void ConfigureCore(string customerGuid)
        {
            if(!customerGuidSet){
               CoreResources.CustomerGuid = customerGuid;
               customerGuidSet = true;
            }
        }
    }
}

The easy way

I have to admit that I was new to Regex and found it a way to play and learn when I wrote this Article. Fellow CodeProject Member Matthew Dennis then pointed at the Guid.TryParse Method which (of course) is much easier to use and let's adapt the GUID format much better than a self tweaked Regex. Here's the sample code he gave me:

using System;
 
namespace ConsoleApplication2
{
    internal static class CoreResources
    {
        static string customerGuid = "{A9526723-C3BC-4A36-ADF8-9AC7CBDCEE52}";
        /// 
        /// GUID to identify the application which uses the Springlog.Core
        /// library.
        /// 
        internal static string CustomerGuid
        {
            get { return CoreResources.customerGuid; }
            set 
            {
                Guid temp;
                if (Guid.TryParse(value, out temp))
                {
                    CoreResources.customerGuid = value; 
                }
                else
                {
                    throw new ArgumentOutOfRangeException("CustomerGuid", "The submitted string is not a valid GUID. Springlog.Core.CoreResources.CustomerGuid "+
                        "needs to be formatted as registry GUID, for example \"{A9526723-C3BC-4A36-ADF8-9AC7CBDCEE52}\"");
                }
            }
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Initial Value = " + CoreResources.CustomerGuid);
                var newGuid = Guid.NewGuid();
 
                string newGuidString = newGuid.ToString();
                Console.WriteLine("Setting Value to " + newGuidString);
                CoreResources.CustomerGuid = newGuidString;
                Console.WriteLine("Current Value = " + CoreResources.CustomerGuid);
 
                newGuidString = "{" + newGuidString + "}";
                Console.WriteLine("Setting Value to " + newGuidString);
                CoreResources.CustomerGuid = newGuidString;
                Console.WriteLine("Current Value = " + CoreResources.CustomerGuid);
 
               newGuidString = "This is not a GUID.";
                Console.WriteLine("Setting Value to " + newGuidString);
                CoreResources.CustomerGuid = newGuidString;
                Console.WriteLine("Current Value = " + CoreResources.CustomerGuid);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception : {0}", ex.Message);
            }
 
            Console.ReadLine();
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Marco Bertschi
Software Developer (Junior)
Switzerland Switzerland
Software Developer (Swiss Federal VET Diploma), experienced with Qt C++, C#, RFC 5424 and Arduino Boards.
Music enthusiast, runner, part-time psychologist for friends, awesome guy and Air Force Sergeant First Class.

You may also be interested in...

Comments and Discussions

 
QuestionLower case letters? Pin
snoopy00116-Jun-15 4:24
membersnoopy00116-Jun-15 4:24 
QuestionWhy not just use Guid.TryParse Pin
Matthew Dennis13-Jun-14 9:44
adminMatthew Dennis13-Jun-14 9:44 
AnswerRe: Why not just use Guid.TryParse Pin
Marco Bertschi14-Jun-14 3:41
protectorMarco Bertschi14-Jun-14 3:41 
GeneralRe: Why not just use Guid.TryParse Pin
Matthew Dennis16-Jun-14 7:25
adminMatthew Dennis16-Jun-14 7:25 
GeneralRe: Why not just use Guid.TryParse Pin
Marco Bertschi16-Jun-14 12:38
protectorMarco Bertschi16-Jun-14 12:38 
QuestionDefault Access Modifiers of class is internal Pin
comiscience13-Jun-14 5:47
professionalcomiscience13-Jun-14 5:47 
GeneralRe: Default Access Modifiers of class is internal Pin
PIEBALDconsult13-Jun-14 6:20
memberPIEBALDconsult13-Jun-14 6:20 
GeneralRe: Default Access Modifiers of class is internal Pin
comiscience13-Jun-14 6:24
professionalcomiscience13-Jun-14 6:24 
Questionsuggestion Pin
joost.versteegen12-Jun-14 23:13
memberjoost.versteegen12-Jun-14 23:13 
GeneralRe: suggestion Pin
Brian A Stephens13-Jun-14 8:53
professionalBrian A Stephens13-Jun-14 8:53 
AnswerRe: suggestion Pin
Marco Bertschi14-Jun-14 3:42
protectorMarco Bertschi14-Jun-14 3:42 
GeneralThoughts Pin
PIEBALDconsult12-Jun-14 13:27
memberPIEBALDconsult12-Jun-14 13:27 
GeneralRe: Thoughts Pin
Marco Bertschi12-Jun-14 16:22
protectorMarco Bertschi12-Jun-14 16:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.160204.4 | Last Updated 15 Jun 2015
Article Copyright 2014 by Marco Bertschi
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid