Reputation: 6866
Consider the following string
string path = @"\\ParentDirectory\All_Attachments$\BATCH_NUMBERS\TS0001\SubDirectory\FileName.txt";
I am trying to modify the path by removing the \\ParentDirectory\All_Attachments$\
. So I want my final string to look like:
BATCH_NUMBERS\TS0001\SubDirectory\FileName.txt
I have come up with the following regex
string pattern = @"(?<=\$)(\\)";
string returnValue = Regex.Replace(path, pattern, "", RegexOptions.IgnoreCase);
With the above if I do Console.WriteLine(returnValue)
I get
\\ParentDirectory\All_Attachments$BATCH_NUMBERS\TS0001\SubDirectory\FileName.txt
So it only removes \
can someone tell me how to achieve this please.
Upvotes: 0
Views: 1080
Reputation: 2703
You can use a combination of Substring()
and IndexOf()
to accomplish your goal:
string result = path.Substring(path.IndexOf("$") + 1);
Upvotes: 0
Reputation: 29647
Using a regex that takes the first 2 groups of (backslash(es) followed by 1 or more non-backslashes). And including the $
and backslash after that.
string returnValue = Regex.Replace(path, @"^(?:\\+[^\\]+){2}\$\\", "");
Or by splitting on $
, joining the string array without it's first element and then trim \
from the start:
string returnValue = string.Join(null, path.Split('$').Skip(1)).TrimStart('\\');
But you'll be using System.Linq for that method to work.
Upvotes: 0
Reputation: 175766
As an alternative avoiding an RE or split/join you could just run along the string until you have seen 4 slashes:
string result = null;
for (int i = 0, m = 0; i < path.Length; i++)
if (path[i] == '\\' && ++m == 4) {
result = path.Substring(i + 1);
break;
}
Upvotes: 0
Reputation: 9566
The code below should do the trick.
string path = @"\\ParentDirectory\All_Attachments$\BATCH_NUMBERS\TS0001\SubDirectory\FileName.txt";
var result = Regex.Replace(path,
@"^ # Start of string
[^$]+ # Anything that is not '$' at least one time
\$ # The '$ sign
\\ # The \ after the '$'
", String.Empty, RegexOptions.IgnorePatternWhitespace);
When executed in LinqPad it gives the following result:
BATCH_NUMBERS\TS0001\SubDirectory\FileName.txt
Upvotes: 2