C# Regex for Guid

I need to parse through a string and add single quotes around each Guid value. I was thinking I could use a Regex to do this but I'm not exactly a Regex guru.

Is there a good Regex to use to identify a Guid?

My second question is once I've found a valid regex I'm assuming I would use Regex.Replace(String, String, MatchEvaluator) but I'm not quite sure of the syntax. Maybe something like:

return Regex.Replace(stringToFindMatch, GuidRegex, match =>
{
    return string.Format("'{0}'", match.Groups[0].ToString());
});

A string that I'm trying to parse may look like this:

"SELECT passwordco0_.PASSWORD_CONFIG_ID as PASSWORD1_46_0_, FROM PASSWORD_CONFIG passwordco0_ WHERE passwordco0_.PASSWORD_CONFIG_ID=baf04077-a3c0-454b-ac6f-9fec00b8e170; @p0 = baf04077-a3c0-454b-ac6f-9fec00b8e170 [Type: Guid (0)]"


This one is quite simple and does not require a delegate as you say.

resultString = Regex.Replace(subjectString, 
     @"(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$", 
     "'$0'");

This matches the following styles, which are all equivalent and acceptable formats for a GUID.

ca761232ed4211cebacd00aa0057b223
CA761232-ED42-11CE-BACD-00AA0057B223
{CA761232-ED42-11CE-BACD-00AA0057B223}
(CA761232-ED42-11CE-BACD-00AA0057B223)

Update 1

@NonStatic makes the point in the comments that the above regex will match false positives which have a wrong closing delimiter.

This can be avoided by regex conditionals which are broadly supported.

Conditionals are supported by the JGsoft engine, Perl, PCRE, Python, and the .NET framework. Ruby supports them starting with version 2.0. Languages such as Delphi, PHP, and R that have regex features based on PCRE also support conditionals. (source http://www.regular-expressions.info/conditional.html)

The regex that follows Will match

{123}
(123)
123

And will not match

{123)
(123}
{123
(123
123}
123)

Regex:

^({)?(\()?\d+(?(1)})(?(2)\))$

The solutions is simplified to match only numbers to show in a more clear way what is required if needed.


Most basic regex is following:

(^([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})$) 

or you could paste it here.

Hope this saves you some time.