Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regx replacing last pattern

I have a string which is a file path:

string test = "C:\Users\Folder\File.txt";

what I wanted to do was to replace everything after the last backslash, i.e the filename by test.
I’m trying to do it like so:

            string test = "C:\\Users\\Folder\\File.txt";
            Regex rx = new Regex(@"\\S*(?!.*\\)");
            string result = rx.Replace(test, "\\test.txt"); 

But this gives me: C:\Users\Folder\test.txtFile.txt" instead of C:\Users\Folder\test.txt", what am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I wouldn’t do that with Regex but Path really:

string test = "C:\\Users\\Folder\\File.txt";
Regex rx = new Regex(@"\\S*(?!.*\\).*");
string result = rx.Replace(test, "\\test.txt");

Console.WriteLine(result);

var betterWay = Path.Combine(Path.GetDirectoryName(test), "test.txt");
Console.WriteLine(betterWay);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading