pushpanjay umrao pushpanjay umrao - 29 days ago 14
C# Question

Dynamic guid extraction using Regex

Hi all I need to extract Guid from the following string

<PageFieldFieldValue:FieldValue FieldName='fa564e0f-0c70-4ab9-b863-0177e6ddd247' runat='server'></PageFieldFieldValue:FieldValue>
<PageFieldRichImageField:RichImageField FieldName="3de94b06-4120-41a5-b907-88773e493458" runat="server"></PageFieldRichImageField:RichImageField>

What i need is to get is "fa564e0f-0c70-4ab9-b863-0177e6ddd247" and "3de94b06-4120-41a5-b907-88773e493458" in this case, However this guid is dynamic and will change every time and there are lot more guids in the string that i have and I need to get all those guids so that I can add them to a colection.
Note: The string is actually an aspx page content. All nodes are different but have same property "FieldName" which I need to get.

I went through the link C# RegEx string extraction and construcked the regex in same way. Here is what I did :

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;


How ever this didnt work for me. I get exception"parsing "FieldName=(?{35})" - Quantifier {x,y} following nothing." while creating the Regex object "reg".

If i dont use {36} which is suppose to be the length of GUiD:

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


I dont get any exception but I dnt get desired result either. match.Groups["ReferenceId"].Value returns empty string

Answer

Try using sth. like that:

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

Explanation

  1. (?<=FieldName=['"]) prepended by FieldName= and " or '
  2. [a-f\d]{8}-[a-f\d][...] followed by GUID (which is what is actually matching)
  3. (?=['"]) followed by " or '

See this in action at Regex101