Reputation: 225
I have strings like this:
Sprites\/tilesTest.png
I wanted to swap \/ with /, and remove extensions, so it would look like this
Sprites/tilesTest
This is what I did:
string GetImageToLoadPath(string path)
{
path = path.Replace("\\/", "/");
path = path.Substring(0, path.LastIndexOf("."));
return path;
}
Was there any better way to do it? Is there any way to do it using regex?
Upvotes: 0
Views: 42
Reputation: 626758
I doubt a regex is the proper tool for handling filepaths like this.
When it comes to directories and file names, Path.Combine
(together with Path.GetDirectoryName
and Path.GetFileNameWithoutExtension
) might be handy, especially when the directory separator is not known. As for the \/
replacement, the way you did seems the best.
Path.Combine(Path.GetDirectoryName(s), Path.GetFileNameWithoutExtension(s))
.Replace(@"\/", "/");
See the C# demo:
using System;
using System.IO;
public class Test
{
public static void Main()
{
var s = @"Sprites\/tilesTest.png";
Console.Write(GetStr(s));
}
public static string GetStr(string s) {
return Path.Combine(Path.GetDirectoryName(s), Path.GetFileNameWithoutExtension(s)).Replace(@"\/", "/");
}
}
So, Path.GetDirectoryName
gets the folder path, Path.GetFileNameWithoutExtension
gets the file name up to but excluding the extension, and Path.Combine
joins the path with the name with the system default directory separator symbol.
Upvotes: 1
Reputation: 685
Try the code below, you can get more details from : Regex.Replace Method (String, String)
string input = @"Sprites\/tilesTest.png";
string pattern = @"(\\)?(.png)?";
string replacement = "";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
Upvotes: 1
Reputation: 77866
I don't see why you need a regular expression at all for this. String functions are really helpful to solve this kind of problem and I would do the same what you already have done but probably make it one liner saying
string GetImageToLoadPath(string path)
{
return path.Replace("\\/", "/").Substring(0, path.LastIndexOf("."));
}
Upvotes: 1