anotheruser
anotheruser

Reputation: 51

Special Multi-Character string splits c#

I have a string [Its not just looking at the GUID pattern in a string, I'm using HtmlAgilityPack to parse and convert them in to htmlnodes, then i have to extract this guid only if the node contains, extractable id and type=\"ClickButton\" value='upload, for simplicity i reduced all the details]

"\r\n                        <extractable id=\"00000000-0000-0000-0000-000000000000\" class=\"myButtonC\" type=\"ClickButton\" value='upload'>\r\n                    "

I want to extract the GUID out of it. It's part of HTML parsing. So I made used the below way and attempted extraction and seems not working. How do I represent "\" " ? and "=\"" ? I used " as \" and \ as \ for literals. Any suggestion?

private static string ExtractId(string str)       
{
    string eId = string.Empty;
    string[] arrys = str.Split(new string[] {@"\"" "}, StringSplitOptions.None);
    foreach (string[] lists in arrys.Select(t => t.Split(new string[] {@"=\"""}, StringSplitOptions.None)))
    {
        for (int j = 0; j < lists.Length; j++)
        {
            if (lists[j].Contains("extractable id"))
            {
                eId = lists[j + 1];
            }
        }
    }
    return eId;
}

Upvotes: 0

Views: 70

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

I suggest using regular expressions to match Guids:

string source = "\r\n <extractable id=\"00000000-0000-0000-0000-000000000000\" class=\"myButtonC\" type=\"ClickButton\" value='upload'>\r\n";

Guid[] result = Regex
  .Matches(
     source, 
    "[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}") 
  .OfType<Match>()
  .Select(match => new Guid(match.Value))
  .ToArray();

Upvotes: 3

Ivan Salo
Ivan Salo

Reputation: 821

How about using Regex

string pattern = @"([a-z0-9]{8}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{12})";

MatchCollection mc = Regex.Matches(your_string, pattern);

foreach (var sGUID in mc)
{
    // do what you want
}

Upvotes: 0

Related Questions