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); 

Validate a String to be in Guid Format in .net C#

Initially, I was using a wrong mechanism to validate a string to be in GUID format. I was doing the following:

string wrongString = String.Empty;
bool IsCorrectGuid = false;
    Guid guid = new Guid(wrongString);
    IsCorrectGuid = true;

However, try-catch is an expensive process so, if you have huge no. strings to validate and most of them will not be a Guid then, this is a very bad way of validation.

The correct way is to use Regex, and if you are working on .Net 4.0 or higher then, you can also use the Guid.TryParse method to achieve the same goal. Following I have demonstrated to validate the string in both ways.


string correctString = Guid.NewGuid().ToString();
Guid guid;
bool guidResTrue = Guid.TryParse(correctString, out guid);


string correctString = Guid.NewGuid().ToString();

//returns true for correct format, case in-sensitive
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);
bool guidResTrue = isGuid.IsMatch(correctString.ToUpper());

Of course, Guid.TryParse should be the preferred way of doing it if, you’re using .Net 4.0 or higher.