Click here to Skip to main content
15,075,638 members
Articles / General Programming / Regular Expressions
Tip/Trick
Posted 12 Jun 2014

Stats

53.1K views
10 bookmarked

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

Rate me:
Please Sign up or sign in to vote.
4.10/5 (7 votes)
14 Jun 2015CPOL1 min read
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:

C#
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.

C#
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:

C#
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:

C#
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
Switzerland Switzerland
I'm a young Software Engineer. Whilst I may accept a 'status quo' as given, it's my responsibility to improve it as soon as the opportunity arises.
Very familiar with the .Net framework since it has been the underlying foundation for most of my professional work so far. I'm that kind of guy who gets stuff done, while I may also improve the way things work whilst I'm at it. Generally can get along well with most people I meet as a professional.
Fervent volunteer firefigter, captain-ranked air force militia spec officer.
Great friend and generally nice to have me around - For a talk, a beer, or a bonfire (I might as well do all of those things combined). Oh, and I really love music - Rock & country that is, mostly.

Comments and Discussions

 
QuestionLower case letters? Pin
snoopy00116-Jun-15 3:24
Membersnoopy00116-Jun-15 3:24 
QuestionWhy not just use Guid.TryParse Pin
Matthew Dennis13-Jun-14 8:44
sysadminMatthew Dennis13-Jun-14 8:44 
AnswerRe: Why not just use Guid.TryParse Pin
Marco Bertschi14-Jun-14 2:41
professionalMarco Bertschi14-Jun-14 2:41 
GeneralRe: Why not just use Guid.TryParse Pin
Matthew Dennis16-Jun-14 6:25
sysadminMatthew Dennis16-Jun-14 6:25 
GeneralRe: Why not just use Guid.TryParse Pin
Marco Bertschi16-Jun-14 11:38
professionalMarco Bertschi16-Jun-14 11:38 
QuestionDefault Access Modifiers of class is internal Pin
comiscience13-Jun-14 4:47
Membercomiscience13-Jun-14 4:47 
GeneralRe: Default Access Modifiers of class is internal Pin
PIEBALDconsult13-Jun-14 5:20
professionalPIEBALDconsult13-Jun-14 5:20 
GeneralRe: Default Access Modifiers of class is internal Pin
comiscience13-Jun-14 5:24
Membercomiscience13-Jun-14 5:24 
Questionsuggestion Pin
joost.versteegen12-Jun-14 22:13
Memberjoost.versteegen12-Jun-14 22:13 
GeneralRe: suggestion Pin
Brian A Stephens13-Jun-14 7:53
professionalBrian A Stephens13-Jun-14 7:53 
AnswerRe: suggestion Pin
Marco Bertschi14-Jun-14 2:42
professionalMarco Bertschi14-Jun-14 2:42 
Yes, you got a point there.

The console is a black place

GeneralThoughts Pin
PIEBALDconsult12-Jun-14 12:27
professionalPIEBALDconsult12-Jun-14 12:27 
GeneralRe: Thoughts Pin
Marco Bertschi12-Jun-14 15:22
professionalMarco Bertschi12-Jun-14 15: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.