采取以下字符串作为输入:从字符串中提取一个文件路径或文件名在C#
var input = @"The file is: ""c:\sampleDirectory\sample subdirectory\sampleFileName.txt\"" which is a text file";
我如何可以提取只能从上面的字符串的文件路径。
使用正则表达式或类似的方法是首选。
采取以下字符串作为输入:从字符串中提取一个文件路径或文件名在C#
var input = @"The file is: ""c:\sampleDirectory\sample subdirectory\sampleFileName.txt\"" which is a text file";
我如何可以提取只能从上面的字符串的文件路径。
使用正则表达式或类似的方法是首选。
编辑:
它可与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路径,但如果您确实必须使用正则表达式或LastIndexOf而不是System中的内置操作,则应该使用Path.DirectorySeparatorChar。 IO.Path – shunty
你给出的解决方案给出了完全错误的结果:[https://dotnetfiddle.net/eYzJsT](https://dotnetfiddle.net/eYzJsT) –
@MostafaArmandi我以为引号内的字符串只是无论如何,我已经像你想要的那样做了,也编辑了答案。这就是你想要的https://dotnetfiddle.net/iz9Lmv – Zeus
如果你的输入模式看起来完全一样,你可以很容易地做到这一点没有正则表达式:
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” – Slai
您可以通过添加代码来生成结果(所以它更通用) –
刚上它最终反斜线和分裂的指标.. –
.Substring之间阅读“”这你有.IndexOf –
确定的位置你真的需要使它与正则表达式复杂吗?为什么不使用System.IO中的Path.GetFileName,Path.GetDirectoryName等(我相信它也是操作系统友好的) – shunty