C# Regex for Guid

后端 未结 6 1252
情歌与酒
情歌与酒 2020-11-27 03:08

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

6条回答
  •  我在风中等你
    2020-11-27 03:23

    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.

提交回复
热议问题