2017-06-14 119 views
0

我从我们的数据库中读取文件名列表,并且任何包含a的文件名不包含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 
} 
+7

我敢肯定有一个Guid的正则表达式在那里 – BradleyDotNET

+2

[C#正则表达式为Guid](http://stackoverflow.com/questions/11040707/ddg#11040993) – hatchet

回答

1

你可以用正则表达式做它像这样:

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

  1. 正则表达式的表现可以说是相当昂贵的
  2. 没有认为t他的正则表达式将抓住100%的案例。

如果处理也文件名有某种分离的说,“_” 如“aaa_bbb_GUID_ccc.txt”
您可以将文件名字符串分割零件,然后在每个部分使用Guid.TryParse() 。

+0

谢谢。我使用了Regex解决方案,因为我的情况不会经常运行,不足以成为性能问题,但基于分隔符分隔的方法是我将来要记住的。 – Imbajoe

相关问题