Izzy
Izzy

Reputation: 6866

Modifying string value

I have a string which is

string a = @"\server\MainDirectory\SubDirectoryA\SubDirectoryB\SubdirectoryC\MyFile.pdf";

The SubDirectoryB will always start with a prefix of RN followed by 6 unique numbers. Now I'm trying to modify SubDirectoryB parth of the string to be replaced by a new value lets say RN012345

So the new string should look like

string b = @"\server\MainDirectory\SubDirectoryA\RN012345\SubdirectoryC\MyFile.pdf";

To achieve this I'm making use of the following helper method

public static string ReplaceAt(this string path, int index, int length, string replace)
{
   return path.Remove(index, Math.Min(length, path.Length - index)).Insert(index, replace);
}

Which works great for now.

However the orginial path will be changing in the near future so it will something like @\MainDirectory\RN012345\AnotherDirectory\MyFile.pdf. So I was wondering if there is like a regex or another feature I can use to just change the value in the path rather than providing the index which will change in the future.

Upvotes: 1

Views: 82

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

Assuming you need to only replace those \RNxxxxxx\ where each x is a unique digit, you need to capture the 6 digits and analyze the substring inside a match evaluator.

var a = @"\server\MainDirectory\SubDirectoryA\RN012345\SubdirectoryC\MyFile.pdf";
var res = Regex.Replace(a, @"\\RN([0-9]{6})\\", m =>
        m.Groups[1].Value.Distinct().Count() == m.Groups[1].Value.Length ?
          "\\RN0123456\\" : m.Value);
// res => \server\MainDirectory\SubDirectoryA\RN0123456\SubdirectoryC\MyFile.pdf

See the C# demo

The regex is

\\RN([0-9]{6})\\

It matches a \ with \\, then matches RN, then matches and captures into Group 1 six digits (with ([0-9]{6})) and then will match a \. In the replacment part, the m.Groups[1].Value.Distinct().Count() == m.Groups[1].Value.Length checks if the number of distinct digits is the same as the number of the substring captured, and if yes, the digits are unique and the replacement occurs, else, the whole match is put back into the replacement result.

Upvotes: 2

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

You can use Regex.Replace to replace the SubDirectoryB with your required value

string a = @"\server\MainDirectory\SubDirectoryA\RN123456\SubdirectoryC\MyFile.pdf";
a = Regex.Replace(a, "RN[0-9]{6,6}","Mairaj");

Here i have replaced a string with RN followed by 6 numbers with Mairaj.

Upvotes: -1

Zesty
Zesty

Reputation: 2991

Use String.Replace

string oldSubdirectoryB = "RN012345";
string newSubdirectoryB = "RN147258";

string fileNameWithPath = @"\server\MainDirectory\SubDirectoryA\RN012345\SubdirectoryC\MyFile.pdf";

fileNameWithPath = fileNameWithPath.Replace(oldSubdirectoryB, newSubdirectoryB);

Upvotes: 0

Related Questions