Home > Software design >  Regex pattern to replace to first segments of file path
Regex pattern to replace to first segments of file path

Time:02-03

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.

CodePudding user response:

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, @"^\\\\[^\\] \\[^\\] \\", "");

CodePudding user response:

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
  • Related