GeekZilla
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; }
Paul is the COO of kwiboo ltd and has more than 20 years 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, ...);
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
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.
phayman said:
Hasn't gone wrong for me for 2 years
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?
phayman said:
Thanks Rik H, removed the mangling
Robert said:
What's wrong with Guid.TryParse();
tclark said:
Rik Hemsley: [a-z] is wrong. You only want to match hex digits.
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
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...
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).
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); }
SP1der said:
Ok i looked into this and decided a better method is to use an extention method. (Server Side Validation) so for anyone who needs to validate on the server and hates RegEx here you go.
http://www.cochrane.ws/post/VBNET-IsGuid-Extension-Method.aspx
Dawson said:
this fixes tclark's problem of mis-matched braces:
^?([0-9a-fA-F]){8}(-([0-9a-fA-F]){4}){3}-([0-9a-fA-F]){12}(?(1)})$
Brandon said:
Thanks for the assist; here is a vb version....
Public Function isGUID(ByVal QFormUID As String) As Boolean Dim guidRegEx As Regex = 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})$") If guidRegEx.IsMatch(QFormUID) Then Return True Else Return False End If End Function
brfenske said:
Here is a version that is a little more "tight":
public static bool IsGuid(string expression) { bool isGuid = false; if (!string.IsNullOrEmpty(expression)) { 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})$"); isGuid = guidRegEx.IsMatch(expression); } return isGuid; }
Fredrik said:
Why not /\w{8}-(\w{4}-){3}\w{12}/