【问题标题】:Dynamic guid extraction using Regex使用正则表达式进行动态引导提取
【发布时间】:2016-11-09 14:52:08
【问题描述】:

大家好,我需要从以下字符串中提取 Guid

<PageFieldFieldValue:FieldValue FieldName='fa564e0f-0c70-4ab9-b863-0177e6ddd247' runat='server'></PageFieldFieldValue:FieldValue> <PageFieldRichImageField:RichImageField FieldName="3de94b06-4120-41a5-b907-88773e493458" runat="server"></PageFieldRichImageField:RichImageField> 在这种情况下,我需要得到的是“fa564e0f-0c70-4ab9-b863-0177e6ddd247”和“3de94b06-4120-41a5-b907-88773e493458”,但是这个guid是动态的,每次都会改变,而且还有更多的guid在我拥有的字符串中,我需要获取所有这些 guid,以便我可以将它们添加到集合中。 注意:字符串实际上是一个aspx页面内容。所有节点都不同,但我需要获取相同的属性“FieldName”。

我浏览了链接C# RegEx string extraction 并以同样的方式构造了正则表达式。这是我所做的:

string s = @"<PageFieldFieldValue:FieldValue FieldName='fa564e0f-0c70-4ab9-b863-0177e6ddd247' runat='server'>
        </PageFieldFieldValue:FieldValue>";
        Regex reg = new Regex(@"FieldName=(?<ReferenceId>{36})");
        Match match = reg.Match(s);
        string guid = match.Groups["ReferenceId"].Value;

这怎么对我不起作用。我得到异常“解析“FieldName =(?{35})” - 量词 {x,y} 什么都没有。在创建 Regex 对象“reg”时。

如果我不使用 {36} 这应该是 GUID 的长度:

Regex reg = new Regex(@"FieldName=(?<ReferenceId>)")

我没有得到任何异常,但我也没有得到想要的结果。 match.Groups["ReferenceId"].Value 返回空字符串

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    尝试使用某物。像这样:

    (?<=FieldName=['"])[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}(?=['"])
    

    说明

    1. (?&lt;=FieldName=['"]) 前面加上 FieldName="'
    2. [a-f\d]{8}-[a-f\d][...] 后跟 GUID(实际匹配的内容)
    3. (?=['"]) 后跟 "'

    看到这个in action at Regex101

    【讨论】:

      【解决方案2】:

      您遇到的问题基本上是您提供了量词 {36} 但没有告诉它要量化什么 - 您需要一些字符匹配表达式就在量词之前。例如,我刚刚添加了“。”在您的示例中的 {36} 之前(意思是“匹配任何 36 个字符”),它似乎有效。哦,我还在“FieldName =”之后添加了缺少的撇号:

      Regex reg = new Regex(@"FieldName='(?<ReferenceId>.{36})");
      

      工作示例:https://regex101.com/r/1tbien/1

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-30
        • 1970-01-01
        • 2023-02-08
        • 1970-01-01
        • 2013-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多