C# Regex For Guid


Answer :

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.


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

Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?