是驱动器路径还是其他路径?检查正则表达式



我想检查它是驱动器路径还是"pol"路径。为此,我已经编写了一个小代码,不幸的是,我总是返回true。

正则表达式可能不正确W?w{1}:{1}[/]{1} .我该怎么做对?路径名始终可以不同,并且不必与极点路径一致。提前谢谢你。


public bool isPolPath(string path)
{
     bool isPolPath= true;
     // Pol-Path:       /Buy/Toy/Special/Clue
     // drive-Path:     Q:Buy/Special/Clue  
     Regex myRegex = new Regex(@"W?w{1}:{1}[/]{1}", RegexOptions.IgnoreCase);
     Match matchSuccess = myRegex.Match(path);
     if (matchSuccess.Success)
         isPolPath= false;
     return isPolPath;
}

您不需要正则表达式来实现此目的。使用System.IO.Path.GetPathRoot .如果给定路径包含驱动器号和空字符串,否则返回X:(其中X是实际驱动器号(。

new List<string> { 
    @"/Buy/Toy/Special/Clue",
    @"q:Buy/Special/Clue",
    @"Buy",
    @"/",
    @"",
    @"q:",
    @"q:/",
    @"q:",
    //@"",    // This throws an exception saying path is illegal
}.ForEach(
    p => Console.WriteLine(Path.GetPathRoot(p))
);
/* This code outputs:
  
  q:
  
  
  q:
  q:
  q:
*/

因此,您的支票可能如下所示:

isPolPath = Path.GetPathRoot(path).Length < 2;

如果您希望使代码更加万无一失,并在传递空字符串时防止异常,则需要确定空(或空(字符串是 pol 路径还是驱动器路径。根据决定,检查将是

sPolPath = string.IsNullOrEmpty(path) || Path.GetPathRoot(path).Length < 2;

if (string.IsNullOrEmpty(path))
    sPolPath = false;
else
    sPolPath = Path.GetPathRoot(path).Length < 2;

最新更新