Extract all the Guids from a string C#

This is one of the rare requirement where I had to extract all the Guid from a string and then do the further processing. Now, to do that, I have used Regex.Matches. It will return a MatchCollection containing each Guid. For a string with no Guid, it will return a MatchCollection of length 0.

string strGuid = "5102d73a-1b0b-4461-93cd-0c024738c19e;#5102d73a-1b0b-4461-93cd-0c024733d52d";
string strNoGuid = "someTextButNoGuid";

string pattern = @"([a-z0-9]{8}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{12})";

MatchCollection mc;

//MatchCollection of length 2
mc = Regex.Matches(strGuid, pattern);

//MatchCollection of length 0
mc = Regex.Matches(strNoGuid, pattern); 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s