Cole W Cole W - 2 months ago 33
C# Question

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:

passwordco0_.PASSWORD_CONFIG_ID as PASSWORD1_46_0_,
PASSWORD_CONFIG passwordco0_
@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, 

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


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

The regex that follows Will match


And will not match




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