You are not Logged in
Would you like to Login or Register

Today is: Friday, 05 September, 2008
Check this months hot topics

IsGuid() (Regular Expression Guid Match)

A regular expression for validating a string as being a Guid is..

@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$"

Example usage

Below is a function I try to keep handy which tests a string for a Guid and returns True or False.

public static bool IsGUID(string expression)
{
    if (expression != null)
    {
        Regex guidRegEx = new Regex(@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");

        return guidRegEx.IsMatch(expression);
    }
    return false;
}


kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Paul Hayman Skype
Author : Paul Hayman
Published : Wednesday, 14 June, 2006

Paul is the COO of kwiboo ltd consultant and has more than a decade of IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services. Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Comments

mcgurk said:

if(expression == null or expression.Length < 36) return false;

return Regex.IsMatch(expression, ...);

July 24, 2007 - 2:20 PM

tclark said:

Shorter version:

^{?([0-9a-fA-F]){8}(-([0-9a-fA-F]){4}){3}-([0-9a-fA-F]){12}}?$

BUT, both our versions match:

things like:

{CA761232-ED42-11CE-BACD-00AA0057B223

which is wrong

July 24, 2007 - 9:24 PM

TopBanana said:

This is just asking to go wrong and spoil someone's day six months down the line. Just try to instantiate a new Guid and catch FormatException.

July 25, 2007 - 1:45 PM

phayman said:

Hasn't gone wrong for me for 2 years :)

July 25, 2007 - 3:08 PM

Rik Hemsley said:

You could do this, which is at least correct:

        public static bool IsGuid(string text)
        {
                return
                (
                        new Regex
                        (@"
                                (
                                        \A{
                                                [a-z\d]{8}
                                                (-[a-z\d]{4}){3}
                                                -[a-z\d]{12}
                                        }\z
                                )
                                |
                                (
                                        \A
                                                [a-z\d]{8}
                                                (-[a-z\d]{4}){3}
                                                -[a-z\d]{12}
                                        \z
                                )
                        ",
                                        RegexOptions.IgnoreCase
                                |        RegexOptions.IgnorePatternWhitespace
                                |        RegexOptions.CultureInvariant


                        )
                ).IsMatch(text);
        }

Or you could do as suggested previously and catch FormatException, which I'd consider equally valid.

Let's see how well this site mangles my code, shall we?

July 25, 2007 - 3:39 PM

phayman said:

Thanks Rik H, removed the mangling :)

July 25, 2007 - 4:47 PM

Robert said:

What's wrong with Guid.TryParse();

July 25, 2007 - 7:19 PM

tclark said:

Rik Hemsley: [a-z] is wrong. You only want to match hex digits.

July 26, 2007 - 2:55 AM

Anastasiosyal said:

The problem with Guid.TryParse is that it does not exist!

I think a TryParse method would be more consistent with the FrameWork. (And with extension methods it could also be added to the Guid class - in the not so distant future)

For this reason I prefer this Implementation

http://geekswithblogs.net/colinbo/archive/2006/01/18/66307.aspx

And Here is a link with a feature request for Microsoft to implement it:

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94072

and here is the link with feedback on the issue with proposed workaround and some tests.

http://connect.microsoft.com/VisualStudio/feedback/Workaround.aspx?FeedbackID=94072

Trapping the error would be slow that's the purpose Paul has created this function in the first place!

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94072

July 26, 2007 - 10:22 AM

tclark said:

Curiously though, TryParse DOES exist on the Guid class, it's just private. You'd think they could have just made it public...

July 26, 2007 - 2:11 PM

GaryGo said:

"Just try to instantiate a new Guid and catch FormatException."

This works, but it's inelegant and can be slow. IMHO, validating with a reg ex is more elegant and should run faster than to catch the exception because you're too lazy to validate. I'm just one of those guys who feels that throwing an exception after a bad user entry (implicit validation) is not as good as a reg ex (explicit validation).

March 24, 2008 - 4:09 PM

Tolgahan Albayrak said:

this one catches all kinds of guids in following formats

('d' represents a hexadecimal digit whose case is ignored): 32 contiguous digits: dddddddddddddddddddddddddddddddd or- Groups of 8, 4, 4, 4, and 12 digits with hyphens between the groups. The entire GUID can optionally be enclosed in matching braces or parentheses: dddddddd-dddd-dddd-dddd-dddddddddddd -or- {dddddddd-dddd-dddd-dddd-dddddddddddd} -or- (dddddddd-dddd-dddd-dddd-dddddddddddd) -or Groups of 8, 4, and 4 digits, and a subset of eight groups of 2 digits, with each group prefixed by "0x" or "0X", and separated by commas. The entire GUID, as well as the subset, is enclosed in matching braces: {0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}

Regular Expression:

        static readonly Regex regGuid =

            new Regex

                (@"

                    ^(

                        (

                            \A\(

                                [a-f\d]{8}

                                (-[a-f\d]{4}){3}

                                -[a-f\d]{12}

                            \)\z

                        )

                        |

                        (

                            \A\{

                                [a-f\d]{8}

                                (-[a-f\d]{4}){3}

                                -[a-f\d]{12}

                            \}\z

                        )

                        |

                        (

                            \A\{\s*

                                0x[a-f\d]{8}\s*,\s*

                                (0x[a-f\d]{4}\s*,\s*){2}

                                \{\s*

                                    (0x[a-f\d]{2}\s*,\s*){7}

                                    0x[a-f\d]{2}\s*

                                \}\s*

                            }\z

                        )

                        |

                        (

                            \A

                                [a-f\d]{32}

                            \z

                        )

                    )$

                ",

                  RegexOptions.Compiled | 

                  RegexOptions.IgnorePatternWhitespace | 

                  RegexOptions.IgnoreCase

              );

Using:

        public static bool IsGuid(string g)

        {

            return !string.IsNullOrEmpty(g) || regGuid.IsMatch(g);

        }

June 12, 2008 - 3:15 PM

Add Comment

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views