【问题标题】:Extract a file path or file name from a string in C#从 C# 中的字符串中提取文件路径或文件名
【发布时间】:2017-03-06 18:33:46
【问题描述】:

将以下字符串作为输入:

var input = @"The file is: ""c:\sampleDirectory\sample subdirectory\sampleFileName.txt\"" which is a text file";

如何仅从上述字符串中提取文件路径。
首选使用 Regex 或类似方法。

【问题讨论】:

  • 只要得到最后一个反斜杠的索引并在它上面分割..
  • .Substring to read between "" 你用 .IndexOf 确定的位置
  • 你真的需要用正则表达式让它变得复杂吗?为什么不使用 System.IO 中的 Path.GetFileName、Path.GetDirectoryName 等(我相信它对操作系统也很友好)
  • 或者看看MS在GitHub source上是怎么做的
  • @shunty 这些方法确实适用于纯路径。但是在我给定的字符串中,路径混合在一个长字符串中。

标签: c# string


【解决方案1】:

已编辑:

可以使用LastIndexOf 完成,正如 eocron 所回答的那样。

但这是一个正则表达式解决方案:

Match match = Regex.Match(input, @"""(.*)\\(.*\..*)[\\]?""", RegexOptions.IgnoreCase);

if (match.Success)
{   
    string path = match.Groups[1].Value;
    string filename = match.Groups[2].value;
}

【讨论】:

  • 我意识到这个问题显然有一个 Windows 路径,但如果你真的必须使用 regex 或 LastIndexOf 而不是 System.IO.Path 中的内置操作,你可能应该使用 Path.DirectorySeparatorChar >
  • 您对给定样本的解决方案给了我完全错误的结果:https://dotnetfiddle.net/eYzJsT
  • @MostafaArmandi 我认为引号内的字符串只给出了。无论如何,我已经按照您的意愿完成了,也编辑了答案。这是你想要的dotnetfiddle.net/iz9Lmv
【解决方案2】:

如果您的输入模式看起来完全像这样,您可以在没有 Regex 的情况下轻松做到这一点:

var magic1 = 14;//index of first quotation mark
var magic2 = 22;//suffix index of last quotation mark
var result = str.Substring(magic, str.Lenght-magic2-magic1);

【讨论】:

  • 魔法答案不适用于 SO :[ 当然实际文件不是“sampleFileName.txt”
  • 在这种情况下,您可以通过添加代码来生成 14/22 的结果来改进这一点。 (所以它更通用)
猜你喜欢
  • 2010-11-09
  • 2012-06-24
  • 2011-03-10
  • 1970-01-01
  • 2018-11-16
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多