我有一个字符串,除其他外,包含一个完整的文件路径。我想去掉文件路径的目录部分并返回字符串的其余部分。下面是一个示例:
"这 - 字符串 - 是 1 个文本字符串,其中包含/this/full/file.path。
我想简化为:
"这个 - 字符串 - 是 1 个带有 file.path 的文本字符串。">
任何想法如何使这个工作?
使用 ([^/]*$( 很好,但会去掉文件路径之前的所有字符。我很难弄清楚如何将其分解为第一个/之前的部分和之后的部分,并对第二个部分进行替换。
谢谢!
/.*/
试试这个。替换为 empty string
。请参阅演示。
https://regex101.com/r/vN3sH3/9
或
[^s]*/.*/
如果你有像This - string - is 1 string of text with dsfsdf/this/full/file.path in it
这样的字符串.请参阅演示。
https://regex101.com/r/vN3sH3/11
另一种选择可能是使用 Path.GetFileName
(MSDN 示例(
string fileName = @"C:mydirmyfile.ext";
string path = @"C:mydir";
string result;
result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
fileName, result);
result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path, result);
// This code produces output similar to the following:
//
// GetFileName('C:mydirmyfile.ext') returns 'myfile.ext'
// GetFileName('C:mydir') returns ''
不要使用正则表达式。
使用 System.IO.Path.GetFileName("/this/full/file.path"(;