Lev Kostychenko
Lev Kostychenko

Reputation: 125

Regex pattern to replace to first segments of file path

I have such types of file paths:

  1. \\server\folder\folder1\folder3\someFile.txt,
  2. \\otherServer\folder123\folder1\folder3\someFile.txt
  3. \\serv\fold\folder3\folder4\someFile.txt

I need to remove the first two segments of this path to make them as follows:

  1. folder1\folder3\someFile.txt,
  2. folder1\folder3\someFile.txt
  3. folder3\folder4\someFile.txt

I'm doing it with c# and Regex.Replace but need a pattern. Thanks.

Upvotes: 0

Views: 334

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

It seems, that you work files' paths, and that's why I suggest using Path not Regex:

using System.IO;

...

string source = @"\\serv\fold\folder3\folder4\someFile.txt";

var result = Path.IsPathRooted(source)
  ? source.Substring(Path.GetPathRoot(source).Length + 1)
  : source;

If you insist on regular expressions then

string result = Regex.Replace(source, @"^\\\\[^\\]+\\[^\\]+\\", "");

Upvotes: 1

Ishwor Khatiwada
Ishwor Khatiwada

Reputation: 174

You can use the following regular expression pattern to remove the first two segments: ^\\[^\\]+\\[^\\]+\\

you can use Regex.Replace in C# example:

string input = "\\\\server\\folder\\folder1\\folder3\\filename.txt";
string pattern = "^\\\\[^\\\\]+\\\\[^\\\\]+\\\\";
string replacement = "";

var result = Regex.Replace(input, pattern, replacement);

 output:
folder1\folder3\filename.txt

Upvotes: 1

Related Questions