如何判断字符串是否包含Guid作为子字符串?

时间:2017-06-14 22:29:39

标签: c#

我正在从我们的数据库中读取文件名列表,并且任何包含不包含guid的文件名都被视为包含在模板中的文件。文件列表可以包含文件,其中一些文件具有guid(模板的一部分),而其他文件没有guid(不是来自模板)。如何区分具有guid的文件和没有guid的文件?

以下是一个例子:

List<string> spotFiles = DAL.HtmlSpot.GetSpotMedia(); //Returns {"manifest.xml", "attributes-97c23e02-e216-431b-9b6b-c5852962e92d.png"}

foreach(string file in spotFiles)
{
    //If file contains a guid as a substring
        //Handle template file
    //Else
        //Handle non-template file
}

1 个答案:

答案 0 :(得分:1)

你可以像这样使用Regex:

List<string> spotFiles = DAL.HtmlSpot.GetSpotMedia(); //Returns {"manifest.xml", "attributes-97c23e02-e216-431b-9b6b-c5852962e92d.png"}

foreach(string fileName in spotFiles)
{

var guidMatch = Regex.Match(fileName, @"(\{){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}",
        RegexOptions.IgnoreCase);

    if (guidMatch.Success)
    {
        //Handle template file
    }
    else
    {
        //Handle non-template file
    }
}

<强> BUT

  1. 正则表达式的性能可能非常昂贵
  2. 没有人认为正则表达式会抓住100%的案例。
  3. 如果您处理的文件名也有某种分隔,请说&#34; _&#34; 例如&#34; aaa_bbb_GUID_ccc.txt&#34;
    你可以将文件名字符串拆分为部分,然后在每个部分使用Guid.TryParse()。

相关问题