Home > Enterprise >  Regx replacing last pattern
Regx replacing last pattern

Time:04-27

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?

CodePudding user response:

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);

CodePudding user response:

.Net has built-in functions for this. Use the Path class:

var path = @"C:\Users\Folder\File.txt";
var directory = Path.GetDirectoryName(path);
var result = Path.Combine(directory, "test.txt");

CodePudding user response:

A much simpler method that doesn't use lookarounds

^(. \\)(. )$

Greedily match all characters up to the last backslash as the first group, then capture all remaining characters as the second group.

string test = @"C:\Users\Folder\File.txt";
var pattern = new System.Text.RegularExpressions.Regex(@"(^. \\)(. )$");
var match = pattern.Match(test);
Console.WriteLine(match.Groups[1].Value);
Console.WriteLine(match.Groups[2].Value);

Group 1 will be C:\Users\Folder\, and group 2 will be File.txt.

This comes with the limitations that it will only accept backslashes as seperators.

  • Related