Find matching guid in string

You may use Guid.TryParse on splitted array. Something like:

string findGuid = "hi sdkfj 1481de3f-281e-9902-f98b-31e9e422431f sdfsf 1481de3f-281e-9902-f98b-31e9e422431f";
string[] splitArray = findGuid.Split();
List<Guid> listofGuid = new List<Guid>();
foreach (string str in splitArray)
{
    Guid temp;
    if (Guid.TryParse(str, out temp))
        listofGuid.Add(temp);
}

This will give you two items in the list of Guid

EDIT: For the new string as per comment of the OP,

string findGuid="hi sdkfj x-Guid:1481de3f-281e-9902-f98b-31e9e422431f sdfsf x-Guid:1481de3f-281e-9902-f98b-31e9e422431f"

Multiple split delimiters may be specified something like:

string[] splitArray = findGuid.Split(' ', ':');

If you would like to get the GUID using a Regex pattern. Then, try this pattern

(\{){0,1}[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}(\}){0,1}

Example

string findGuid = "hi sdkfj 1481de3f-281e-9902-f98b-31e9e422431f sdfsf 1481de3f-281e-9902-f98b-31e9e422431f"; //Initialize a new string value
MatchCollection guids = Regex.Matches(findGuid, @"(\{){0,1}[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}(\}){0,1}"); //Match all substrings in findGuid
for (int i = 0; i < guids.Count; i++)
{
    string Match = guids[i].Value; //Set Match to the value from the match
    MessageBox.Show(Match); //Show the value in a messagebox (Not required)
}

Regex Matcher matching TWO GUIDs from a string

Notice: I've used the same pattern you've provided but simply removed the ^ character which indicates that the expression must match from the start of the string. Then, removed the $ character which indicates that the expression must match from the end of the string.

More information about Regular Expressions can be found here:
Regular Expressions - a Simple User Guide and Tutorial

Thanks,
I hope you find this helpful :)


Looks like You use incorrect regular expression. If You need guid

{8}-{4}-{4}-{4}-{12}

should be like

[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}

You may try in this way:

string findGuid="hi sdkfj 1481de3f-281e-9902-f98b-31e9e422431f sdfsf 1481de3f-281e-9902-f98b-31e9e422431f";
    string regexp = @"[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}";
    if (Regex.IsMatch(findGuid, regexp))
    {
        Console.WriteLine(
        Regex.Match(findGuid, regexp).Value
        );

    }

Tags:

C#

Regex