168

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)]"

Cole W
  • 15,123
  • 6
  • 51
  • 85
  • 7
    That is SQL, and you should be using SQL parameters. – jrummell Jun 14 '12 at 20:18
  • 2
    Why would you use REgex there is a GUID.IsGUid – Micah Armantrout Jun 14 '12 at 20:19
  • Actually, there is a parameter, but its the same as the value in the where clause. Where is this coming from? A profiler? – jrummell Jun 14 '12 at 20:25
  • @jrummell This is coming from a profiler yeah. I'm trying to convert the output such that I can copy and paste it and run it in SQL Management Studio. This is for logging purposes only. It will still be ran as parametrized sql. – Cole W Jun 14 '12 at 20:28
  • Which profiler? There might be a way to modify the output. MiniProfiler, for example, has an EF specific formatter that generates SSMS friendly sql. – jrummell Jun 14 '12 at 20:37
  • @jrummel It's a custom log4net appender. This output is being generated by NHibernate. The custom log4net appender is based on this one: http://gedgei.wordpress.com/2011/09/03/logging-nhibernate-queries-with-parameters/ – Cole W Jun 14 '12 at 20:39
  • @MicahArmantrout - RegEx can be helpful when testing with NUnit or other situations where a RegEx is accepted as an argument to another routine that does the string comparison. For example: StringAssert.IsMatch("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}", MyInstance.GUID); – ftexperts Mar 20 '14 at 18:58
  • @MicahArmantrout Is there?! My intellisense claims that there's no *IsGuid* in the *Guid* class... – Konrad Viltersten May 30 '14 at 03:05
  • 1
    Guess in was wrong I out http://msdn.microsoft.com/en-us/library/system.guid.tryparse(v=vs.110).aspx – Micah Armantrout May 30 '14 at 03:08
  • @Micah Armantrout - I want a regex so I can do client side validation before submittal. I can't use the GUID methods in my regular expression validator. – yougotiger Jun 01 '20 at 21:47
  • https://stackoverflow.com/questions/25131143/javascript-string-to-guid or https://stackoverflow.com/questions/8368381/regular-expression-retrieve-the-guid-inside-parenthesis – Micah Armantrout Jun 02 '20 at 17:44

7 Answers7

237

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.

buckley
  • 13,690
  • 3
  • 53
  • 61
  • As written, this would not have worked for all of the valid types of GUIDs (hence the update). – senfo Dec 24 '15 at 15:40
  • 6
    This does not account for lower case characters which would be a valid case. Use ^[{|\(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[\)|}]?$ or use the /i flag – Michael Brown Feb 16 '16 at 22:35
  • @MichaelBrown It does match case insensitive, see RegexOptions.IgnoreCase in the code sample. – buckley Feb 29 '16 at 14:50
  • I'm afraid this is not fully right: "{CA761232-ED42-11CE-BACD-00AA0057B223)" will be accepted as well but you know it is not a right one. – NonStatic Oct 29 '16 at 04:10
  • @NonStatic Yes that's right. If needed you can use my update 1 to prevent this false positive – buckley Nov 02 '16 at 09:27
  • @buckley Does your update 1 solution match `{(123)}` ? If yes could be not correct consider it a Guid... – Antonio Manello Nov 22 '17 at 14:39
  • @AntonioManello {(123)} is not matched as it is not a correct GUID. The update was for cases where the starting delimiter differs from the ending delimiter – buckley Nov 23 '17 at 08:49
  • Was looking for something that could be used to identify only valid Guids. Building off of this answer, this is the solution that ended up working for me: `^({)?(?(1)|(\()?)[0-9A-F]{8}(-)?([0-9A-F]{4}(?(3)-)){3}[0-9A-F]{12}(?(1)}|(?(2)\)))$` – tdashroy Dec 08 '17 at 23:02
  • 3
    The regex will also allow less than 4 minus signs. Fyi for those who care about this. For those who don't care, here is a simpler regex that allows many more false positives: `[0-9a-fA-F\-]{32,36}`. – usr Jan 11 '18 at 14:31
  • @usr Matching guids with less than 4 minus signs is a consequence of allowing a guid with no minus signs at all and writing a regex that's (relatively) small. Using alternation (pipe | symbol) makes it possible to write out the different cases. That will make the regex longer and, arguably, more readable in addition to addressing not mixing delimiters without regex conditionals. – buckley Mar 15 '18 at 09:37
  • 1
    Doesn't work for `https://support.office.com/en-us/article/poisson-function-d81f7294-9d7c-4f75-bc23-80aa8624173a` – zmechanic May 23 '18 at 15:50
  • That's because the regex matches guids that stand on their own on 1 line (and not part of something else like and url) – buckley Jan 30 '19 at 12:05
  • For some reason doesn't work on this GUID: f150ab2e-c5ab-4b89-9ab7-77da01243190 – Roger Far Mar 09 '19 at 18:24
  • @Farlock85 That's because the api that I use (.net) is told to ignore the case. Your guid is in lowercase. Can you tell your api to ignore the case as well? – buckley Mar 12 '19 at 11:00
68

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.

Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265
  • Not quite as full as the suggested answer, but +1 for the regex101.com link. – Jim Billig Aug 26 '16 at 22:06
  • 15
    Removed the repetition: `[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}` The dashes could be made optional: `[0-9A-Fa-f]{8}-?([0-9A-Fa-f]{4}-?){3}[0-9A-Fa-f]{12}`. – Louis Somers Jul 12 '19 at 12:29
  • @LouisSomers the group can be made non-capturing by adding `?:` after the opening parentheses. – OfirD Sep 21 '22 at 21:16
35

For C# .Net to find and replace any guid looking string from the given text,

Use this RegEx:

[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?

Example C# code:

var result = Regex.Replace(
      source, 
      @"[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?", 
      @"${ __UUID}", 
      RegexOptions.IgnoreCase
);

Surely works! And it matches & replaces the following styles, which are all equivalent and acceptable formats for a GUID.

"aa761232bd4211cfaacd00aa0057b243" 
"AA761232-BD42-11CF-AACD-00AA0057B243" 
"{AA761232-BD42-11CF-AACD-00AA0057B243}" 
"(AA761232-BD42-11CF-AACD-00AA0057B243)" 
GDroid
  • 1,254
  • 1
  • 16
  • 36
  • 6
    The accepted answer did not work for me but this one did! – Merin Nakarmi Jan 14 '19 at 18:47
  • One problem here. Guid will only contain hexadecimal numbers. Thus letters from a-z and A-Z are not acceptable but only a-f and A-F. Otherwise it would accept any text with 32 characters as a valid Guid. – Merin Nakarmi Jan 24 '19 at 18:26
  • Ditto - The accepted answer did not work for me but this one did! – Greg Trevellick Aug 06 '20 at 20:35
  • You set `RegexOptions.IgnoreCase` - because of this [a-f0-9] would be enough. – kara Dec 17 '20 at 06:56
  • Yup, agree, ignored removing it as it doesn't hurt. IgnoreCase was placed in for initial answer and then I added [a-f0-9] in regex if I remember correctly. – GDroid Dec 17 '20 at 08:07
9

In .NET Framework 4 there is enhancement System.Guid structure, These includes new TryParse and TryParseExact methods to Parse GUID. Here is example for this.

    //Generate New GUID
    Guid objGuid = Guid.NewGuid();
    //Take invalid guid format
    string strGUID = "aaa-a-a-a-a";

    Guid newGuid;

    if (Guid.TryParse(objGuid.ToString(), out newGuid) == true)
    {
        Response.Write(string.Format("<br/>{0} is Valid GUID.", objGuid.ToString()));
    }
    else
    {
        Response.Write(string.Format("<br/>{0} is InValid GUID.", objGuid.ToString()));
    }


    Guid newTmpGuid;

    if (Guid.TryParse(strGUID, out newTmpGuid) == true)
    {
        Response.Write(string.Format("<br/>{0} is Valid GUID.", strGUID));
    }
    else
    {
        Response.Write(string.Format("<br/>{0} is InValid GUID.", strGUID));
    }

In this example we create new guid object and also take one string variable which has invalid guid. After that we use TryParse method to validate that both variable has valid guid format or not. By running example you can see that string variable has not valid guid format and it gives message of "InValid guid". If string variable has valid guid than this will return true in TryParse method.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Jayesh Sorathia
  • 1,596
  • 15
  • 16
  • 7
    The question was asking how to find/extract a GUID from a longer string, not validate a GUID. Suggest you remove this answer. – iCollect.it Ltd May 24 '13 at 07:37
  • 15
    @Micah Armantrout: It may be a "good" answer, but it is not an answer for *this question*. If you just put any answer anywhere you like, it kind of defeats the purpose of StackOverflow :) – iCollect.it Ltd May 30 '14 at 06:43
  • 8
    Well, for someone like me searching for a "regex for guid", this answer was really the most helpful - I don't __really__ need a regex, I need to match GUIDs, and this page is the first result for "regex to detect guid" on Google currently. – Dan Field Nov 02 '15 at 21:18
  • 3
    Seconding @Dan Field. I came here on a searching for regex for guid and found this answer to be what I really wanted. The purpose of StackOverflow was thus fulfilled. – JLScott Jun 23 '16 at 17:53
  • This is not the relevant answer but it of course is helpful. One vote from me. :) – Merin Nakarmi Jan 24 '19 at 18:29
9

You can easily auto-generate the C# code using: http://regexhero.net/tester/.

Its free.

Here is how I did it:

enter image description here

The website then auto-generates the .NET code:

string strRegex = @"\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"     {CD73FAD2-E226-4715-B6FA-14EDF0764162}.Debug|x64.ActiveCfg =         Debug|x64";
string strReplace = @"""$0""";

return myRegex.Replace(strTargetString, strReplace);
Contango
  • 76,540
  • 58
  • 260
  • 305
7

I use an easier regex pattern

^[0-9A-Fa-f\-]{36}$
Larissa Savchekoo
  • 6,412
  • 1
  • 13
  • 7
6

To simply match GUID's with hyphens like these:
63F0DA57-5AA2-4271-B9DE-6FD68008EA98
aa76ae52-14f2-5774-A645-9d002a72dec1

I use the following:

[a-fA-F\d]{8}-[a-fA-F\d]{4}-[a-fA-F\d]{4}-[a-fA-F\d]{4}-[a-fA-F\d]{12}
JustAGabriel
  • 61
  • 1
  • 3