用于 Guid 的 C# 正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11040707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:13:48  来源:igfitidea点击:

C# Regex for Guid

c#regex

提问by Cole W

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.

我需要解析一个字符串并在每个 Guid 值周围添加单引号。我想我可以使用正则表达式来做到这一点,但我并不完全是正则表达式大师。

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. Maybe something like:

我的第二个问题是一旦我找到了一个有效的正则表达式,我假设我会使用,Regex.Replace(String, String, MatchEvaluator)但我不太确定语法。也许是这样的:

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

"SELECT passwordco0_.PASSWORD_CONFIG_ID 作为PASSWORD1_46_0_, FROM PASSWORD_CONFIG passwordco0_WHERE passwordco0_.PASSWORD_CONFIG_ID=baf04077-a3c0-454b-ac6f-9fec00b8e170;@4070b8e170;@40ac700d-c8c70f-bc70d-4af)

采纳答案by buckley

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}[)}]?$", 
     "'
ca761232ed4211cebacd00aa0057b223
CA761232-ED42-11CE-BACD-00AA0057B223
{CA761232-ED42-11CE-BACD-00AA0057B223}
(CA761232-ED42-11CE-BACD-00AA0057B223)
'");

This matches the following styles, which are all equivalent and acceptable formats for a GUID.

这与以下样式相匹配,它们都是 GUID 的等效和可接受的格式。

{123}
(123)
123

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

JGsoft 引擎、Perl、PCRE、Python 和 .NET 框架支持条件。Ruby 从 2.0 版开始支持它们。Delphi、PHP 和 R 等具有基于 PCRE 的正则表达式功能的语言也支持条件。(来源http://www.regular-expressions.info/conditional.html

The regex that follows Will match

后面的正则表达式将匹配

{123)
(123}
{123
(123
123}
123)

And will not match

并且不会匹配

^({)?(\()?\d+(?(1)})(?(2)\))$

Regex:

正则表达式:

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

The solutions is simplified to match only numbers to show in a more clear way what is required if needed.

解决方案被简化为仅匹配数字,以便在需要时以更清晰的方式显示所需内容。

回答by Jayesh Sorathia

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.

在 .NET Framework 4 中有增强的 System.Guid 结构,其中包括解析 GUID 的新 TryParse 和 TryParseExact 方法。这是一个例子。

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-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$) 
"""; return myRegex.Replace(strTargetString, strReplace);

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.

在这个例子中,我们创建了一个新的 guid 对象,并采用了一个具有无效 guid 的字符串变量。之后我们使用 TryParse 方法来验证两个变量是否具有有效的 guid 格式。通过运行示例,您可以看到字符串变量没有有效的 guid 格式,它给出了“InValid guid”的消息。如果字符串变量具有有效的 guid,则这将在 TryParse 方法中返回 true。

回答by Contango

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:

这是我如何做到的:

enter image description here

在此处输入图片说明

The website then auto-generates the .NET code:

然后网站会自动生成 .NET 代码:

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

回答by Matas Vaitkevicius

Most basic regex is following:

最基本的正则表达式如下:

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

or you could paste it here.

或者你可以把它贴在这里

Hope this saves you some time.

希望这可以为您节省一些时间。

回答by GDroid

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

对于 C# .Net 从给定文本中查找和替换任何 guid 查找字符串,

Use this RegEx:

使用这个正则表达式:

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

Example C# code:

示例 C# 代码:

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

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

肯定有效!它匹配并替换以下样式,这些样式都是 GUID 的等效和可接受的格式。

##代码##

回答by Larissa Savchekoo

I use an easier regex pattern

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

##代码##