0

I have a text that contains a GUID

Is there a way I can extract the GUID?

var txt = "bbv  nvnvn nvnvnv  d0b992f5-2175-4d8f-9a86-30b61e279340 dsdf";

Expected result is

Guid guid == d0b992f5-2175-4d8f-9a86-30b61e279340; 

Thankful

vahid
  • 11
  • 3

2 Answers2

0

You can use the following code for your GUID pattern (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx):

var input = @"0


I have a text that contains a GUID

Is there a way I can extract the GUID?

var txt= bbv nvnvn nvnvnv d0b992f5-2175-4d8f-9a86-30b61e279340 dsdf;

a ca761232ed4211cebacd00aa0057b223
CA761232-ED42-11CE-BACD-00AA0057B223";

            var pattern = "([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})";

            MatchCollection matches = Regex.Matches(input, pattern);
            foreach (Match match in matches)
            {
                GroupCollection groups = match.Groups;
                Console.WriteLine(groups[1]);
            }

The result would be:

d0b992f5-2175-4d8f-9a86-30b61e279340

CA761232-ED42-11CE-BACD-00AA0057B223

Saeed Aghdam
  • 307
  • 3
  • 11
0

You can try regular expressions and Linq:

  using System.Linq;
  using System.Text.RegularExpressions;

  ...

  string txt = "bbv nvnvn nvnvnv d0b992f5-2175-4d8f-9a86-30b61e279340 dsdf;";

  // All Guids within txt
  Guid[] guids = Regex
    .Matches(txt, "[A-Fa-f0-9]{8}-(?:[A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}")
    .Cast<Match>()
    .Select(match => Guid.Parse(match.Value))
    .ToArray();

If you are looking just for the first guid:

  var match = Regex.Match(text, 
    "[A-Fa-f0-9]{8}-(?:[A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}");

  if (match.Success) {
    Guid guid = Guid.Parse(match.Value);

    //TODO: put relevant code here 
  }
  else {
    // No GUID found
  }

Pattern "[A-Fa-f0-9]{8}-(?:[A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}" stands for

    [A-Fa-f0-9]{8}         - 8 hexadecimal digits
    (?:[A-Fa-f0-9]{4}-){3} - 3 groups of 4 hexadecimal digits
    [A-Fa-f0-9]{12}        - 12 hexadecimal digits  
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215