特殊的多字符串拆分c#

时间:2017-05-02 18:57:10

标签: c# split string-literals

我有一个字符串[它不只是查看字符串中的GUID模式,我使用HtmlAgilityPack解析并将它们转换为htmlnodes,然后我必须提取此guid仅在节点包含,可提取的id和type = \“ClickButton \”value ='upload,为简单起见我减少了所有细节]

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

我想从中提取GUID。它是HTML解析的一部分。所以我使用了以下方式并尝试提取,似乎无法正常工作。我如何表示“\”“?和”= \“”?我使用“as \”和\ as \作为文字。有什么建议吗?

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

2 个答案:

答案 0 :(得分:3)

我建议使用正则表达式来匹配Guid s:

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();

答案 1 :(得分:0)

如何使用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
}