C# 正则表达式将具有完整文件路径的字符串简化为仅包含文件名的原始字符串

本文关键字:字符串 原始 文件名 包含 路径 正则表达式 文件 | 更新日期: 2023-09-27 18:34:34

我有一个字符串,除其他外,包含一个完整的文件路径。我想去掉文件路径的目录部分并返回字符串的其余部分。下面是一个示例:

"这 - 字符串 - 是 1 个文本字符串,其中包含/this/full/file.path。

我想简化为:

"这个 - 字符串 - 是 1 个带有 file.path 的文本字符串。">

任何想法如何使这个工作?

使用 ([^/]*$( 很好,但会去掉文件路径之前的所有字符。我很难弄清楚如何将其分解为第一个/之前的部分和之后的部分,并对第二个部分进行替换。

谢谢!

C# 正则表达式将具有完整文件路径的字符串简化为仅包含文件名的原始字符串

'/.*'/

试试这个。替换为 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:'mydir'myfile.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:'mydir'myfile.ext') returns 'myfile.ext' 
// GetFileName('C:'mydir'') returns ''

不要使用正则表达式。

使用 System.IO.Path.GetFileName("/this/full/file.path"(;