186

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

11
  • 8
    That is SQL, and you should be using SQL parameters. Commented Jun 14, 2012 at 20:18
  • 3
    Why would you use REgex there is a GUID.IsGUid Commented Jun 14, 2012 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? Commented Jun 14, 2012 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. Commented Jun 14, 2012 at 20:28
  • 1
    Guess in was wrong I out msdn.microsoft.com/en-us/library/… Commented May 30, 2014 at 3:08

7 Answers 7

242

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.

Sign up to request clarification or add additional context in comments.

14 Comments

As written, this would not have worked for all of the valid types of GUIDs (hence the update).
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
@MichaelBrown It does match case insensitive, see RegexOptions.IgnoreCase in the code sample.
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}.
Doesn't work for https://support.office.com/en-us/article/poisson-function-d81f7294-9d7c-4f75-bc23-80aa8624173a
|
76

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.

3 Comments

Not quite as full as the suggested answer, but +1 for the regex101.com link.
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}.
@LouisSomers the group can be made non-capturing by adding ?: after the opening parentheses.
43

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

5 Comments

The accepted answer did not work for me but this one did!
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.
Ditto - The accepted answer did not work for me but this one did!
You set RegexOptions.IgnoreCase - because of this [a-f0-9] would be enough.
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.
10

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.

6 Comments

The question was asking how to find/extract a GUID from a longer string, not validate a GUID. Suggest you remove this answer.
@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 :)
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.
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.
This is not the relevant answer but it of course is helpful. One vote from me. :)
|
10

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

1 Comment

I'd also include lower-case characters with a-f to ensure lower-cased GUIDs are also supported.
8

I use an easier regex pattern

^[0-9A-Fa-f\-]{36}$

2 Comments

This will match more than GUIDs
... and it will only match for lines only containing Guid and nothing else.
7

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}

1 Comment

This is the cleanest one (results wise) out of all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.