簡體   English   中英

使用Regex動態提取GUID

[英]Dynamic guid extraction using Regex

嗨,我需要從以下字符串中提取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字符串提取,並以相同的方式構造了regex。 這是我所做的:

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}不跟隨任何內容。” 同時創建正則表達式對象“ reg”。

如果我不使用{36}這應該是GUiD的長度:

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

我沒有任何異常,但我也沒有得到理想的結果。 match.Groups [“ ReferenceId”]。Value返回空字符串

嘗試使用sth。 像那樣:

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

說明

  1. (?<=FieldName=['"])前面加上FieldName ='
  2. [af\\d]{8}-[af\\d] [...]后跟GUID(這實際上是匹配項)
  3. (?=['"])后跟'

在Regex101上實際操作

您遇到的問題基本上是您在提供量詞{36},但沒有告訴它要量化的內容-您需要在量詞之前使用一些字符匹配表達式。 例如,我只是添加了“。” 在您的示例中{36}之前(意思是“匹配任何36個字符”),它似乎可以正常工作。 哦,我還在“ FieldName =“之后添加了缺失的撇號:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM