简体   繁体   English

C# Guid 正则表达式

[英]C# Regex for Guid

I need to parse through a string and add single quotes around each Guid value.我需要解析一个字符串并在每个 Guid 值周围添加单引号。 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?是否有一个好的正则表达式可用于识别 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.我的第二个问题是一旦我找到了一个有效的正则表达式,我假设我会使用Regex.Replace(String, String, MatchEvaluator)但我不太确定语法。 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)]" “选择密码co0_.PASSWORD_CONFIG_ID 为 PASSWORD1_46_0_,从 PASSWORD_CONFIG 密码co0_ WHERE passwordco0_.PASSWORD_CONFIG_ID=baf04077-a3c0-454b-ac6f-9fec00b8e170;@p0 = baf04077-a3c0-454b-ac6f-9fec00b8e170;@p0 = baf04077-a3c0-454b-ac6f-9fec00b8e10)]"

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. 这与以下样式匹配,这些样式都是GUID的等效和可接受的格式。

ca761232ed4211cebacd00aa0057b223
CA761232-ED42-11CE-BACD-00AA0057B223
{CA761232-ED42-11CE-BACD-00AA0057B223}
(CA761232-ED42-11CE-BACD-00AA0057B223)

Update 1 更新1

@NonStatic makes the point in the comments that the above regex will match false positives which have a wrong closing delimiter. @NonStatic在评论中指出上述正则表达式将匹配具有错误结束分隔符的误报。

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. JGsoft引擎,Perl,PCRE,Python和.NET框架支持条件。 Ruby supports them starting with version 2.0. Ruby从2.0版开始支持它们。 Languages such as Delphi, PHP, and R that have regex features based on PCRE also support conditionals. Delphi,PHP和R等具有基于PCRE的正则表达式功能的语言也支持条件。 (source http://www.regular-expressions.info/conditional.html ) (来源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. 希望这能为您节省一些时间。

You can easily auto-generate the C# code using: http://regexhero.net/tester/ . 您可以使用以下命令轻松自动生成C#代码: http//regexhero.net/tester/

Its free. 免费。

Here is how I did it: 我是这样做的:

在此输入图像描述

The website then auto-generates the .NET code: 然后该网站自动生成.NET代码:

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

For C# .Net to find and replace any guid looking string from the given text, 对于C#.Net来查找和替换给定文本中的任何guid外观字符串,

Use this RegEx: 使用此RegEx:

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

Example C# code: 示例C#代码:

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. 它匹配并替换以下样式,这些样式都是GUID的等效和可接受的格式。

"aa761232bd4211cfaacd00aa0057b243" 
"AA761232-BD42-11CF-AACD-00AA0057B243" 
"{AA761232-BD42-11CF-AACD-00AA0057B243}" 
"(AA761232-BD42-11CF-AACD-00AA0057B243)" 

In .NET Framework 4 there is enhancement System.Guid structure, These includes new TryParse and TryParseExact methods to Parse GUID. 在.NET Framework 4中有增强的System.Guid结构,其中包括用于解析GUID的新TryParse和TryParseExact方法。 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. 在这个例子中,我们创建了新的guid对象,并且还获取了一个具有无效guid的字符串变量。 After that we use TryParse method to validate that both variable has valid guid format or not. 之后我们使用TryParse方法验证两个变量是否都有有效的guid格式。 By running example you can see that string variable has not valid guid format and it gives message of "InValid guid". 通过运行示例,您可以看到字符串变量没有有效的guid格式,并且它给出了“InValid guid”的消息。 If string variable has valid guid than this will return true in TryParse method. 如果字符串变量具有有效的guid,那么它将在TryParse方法中返回true。

我使用更简单的正则表达式模式

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

To simply match uppercase GUID's with hyphens like these:简单地将大写 GUID 与连字符匹配,如下所示:
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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM