Sajad Ahanger
Sajad Ahanger

Reputation: 65

Extract a GUID from a string. How can I do it?

I have a string in this format:

"object": "Board-f330c10a-a9eb-4253-b554-43ed95c87242"

and I want to extract guid from it.I was trying like this:

Guid.Parse(followActivity.Object.Split('-').Skip(1).FirstOrDefault());

but it takes only the first part of the guid string. How can I extract whole guid?

Can anybody help.

Upvotes: 0

Views: 2644

Answers (4)

ikkentim
ikkentim

Reputation: 1648

If the format is always the same, you could use string.Split()

Guid.Parse(followActivity.Object.Split(new char[]{'-'}, 2)[1]));

Upvotes: 1

Captain Kenpachi
Captain Kenpachi

Reputation: 7215

Or just

Guid.Parse(followActivity.Object.Replace("Board-",""));

Upvotes: 2

mukesh kudi
mukesh kudi

Reputation: 729

Try this

 Guid.Parse(string.Join("-",followActivity.Object.Split('-').Skip(1)))

Upvotes: 2

sujith karivelil
sujith karivelil

Reputation: 29036

Try something like this Example , if every input follows the same patter like Board-:

string complexGuid = "Board-f330c10a-a9eb-4253-b554-43ed95c87242";
string extractedGuid = complexGuid.Substring(complexGuid.IndexOf('-') +1 );

Here complexGuid.IndexOf('-') will return the first index of the '-' which is the - after the Board in the given example. we need to skip that also so add a +1 so that .Substring() will give you the expected output for you.

Upvotes: 4

Related Questions