Christopher Green

Now with more Vitamin C!
posts - 41, comments - 30, trackbacks - 1

The correct way to test if a string is a Guid

Recently I've had a few scenarios where I needed to test if a string was a guid.  I had a dirty solution using a try/catch but today I needed to perform this test thousands of times and this was much too slow.  So a quick search turned up this beauty and shows the "right" way to perform this test.

 using System.Text.RegularExpressions;
   
 private static Regex isGuid = 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}$", RegexOptions.Compiled);
    internal static bool IsGuid(string candidate, out Guid output)
    {
        bool isValid = false;
        output = Guid.Empty;

        if (candidate != null)
        {
            if (isGuid.IsMatch(candidate))
            {
                output = new Guid(candidate);
                isValid = true;
            }
        }
        return isValid;
    }

Print | posted on Thursday, May 25, 2006 12:43 PM |

Feedback

Gravatar

# re: The correct way to test if a string is a Guid

TypeDescriptor.GetConverter(Guid).IsValid(candidate)

(Using the GuidConverter class...)
5/26/2006 2:04 PM | Merrion
Gravatar

# re: The correct way to test if a string is a Guid

Wish it were that simple. I tried this but it returned true on non-guids
10/4/2006 9:25 PM | chris
Comments have been closed on this topic.

Powered by: