Archive Blogs
February, 2010

<< Back to current Blogs

More Archives

2010 February ( 2 )
2009 July ( 1 )
2009 June ( 1 )
2009 May ( 2 )
2009 April ( 2 )

Avatar

Extracting a Guid from of a string in .NET

02/16/2010 at 07:46 PM

I needed to pull a Guid out of a string (more on why later) and didn't find any quick answers with using Regex, except for Guid syntax validation (e.g. IsMatch)

Going from IsMatch to pulling the match is not hard, so I came up with the following. I'm sure my expression is not as sophisticated as it could be. If you have a better pattern, please share:

Regex r = new Regex(@"([0-9a-f]{8}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{12})", RegexOptions.Compiled | RegexOptions.IgnoreCase );

string myGuid = r.Match(pullGuidFromMeString).Groups[1].Value;

*Note: I used an unnamed group, so 1 is the starting index.

Why did I need to do this?

I was writing a Web Service test, from the consumer side, and needed to validate that an event log entry was written when an exception was thrown within the service. For security purposes, of course, stack traces nor Exception details are never returned to the consumer. Instead, it's a generic error messages, and in this case, a Guid.

The Guid can be used by consumers during troubleshooting to trace back errors, and root cause, as we log the Guid in the event log with the Exception details.

Never mind how I setup a fixture to create an Exception, just know that I was able take the consumer error message, lookup recent errors in the event log, and if my Guid was in the message, I could then assert the details of error message.

b

Comment:

*Note: All replies subject to moderator approval. Content may be changed or completely removed by the moderator.

Name

Email

Body