简体   繁体   中英

C# regex reduce a string with a full file path to the original string with just the file name

I've got a string that, among other things, contains a full file path. I'd like the strip out the directory portion of the file path and return the rest of the string. Here's an example:

"This - string - is 1 string of text with /this/full/file.path in it."

Which I'd like to reduce to:

"This - string - is 1 string of text with file.path in it."

Any ideas how to make this one work?

Using ([^/]*$) is nice but strips off all the characters before the file path. I'm having a hard time figuring out how to break it into the part before the first / and the part after with doing the substition on the second piece.

Thanks!

\/.*\/

Try this.Replace by empty string .See demo.

https://regex101.com/r/vN3sH3/9

or

[^\s]*\/.*\/

If you have string like This - string - is 1 string of text with dsfsdf/this/full/file.path in it .See demo.

https://regex101.com/r/vN3sH3/11

Another option could be to use Path.GetFileName

(MSDN Example)

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 ''

Don't use a Regex.

use System.IO.Path.GetFileName("/this/full/file.path");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM