Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I want a create a regex to give me part of a file path.
For example:
C:\Users\CoolDude\Documents\Access\Test.pdf

i want the regex to give me only
Documents\Access\Test.pdf

The folder name will not always be "Documents" after the username.

Any Idea?

What I have tried:

Still trying. No working solution so far.
Posted
Updated 14-Jul-17 20:01pm
Comments
Michael_Davies 14-Jul-17 16:16pm    
If your certain that the C:\Users\SomeUserNameHere\... never changes then all you have to do is extract the string part after the third backslash which is possible in Regex, you could also split the string to an array using \ to get the components.

Using split;

Dim sIn As String = "C:\Users\CoolDude\Documents\Access\Test.pdf"
Dim sOut() As String

sOut = sIn.Split("\\")

The array sOut would then have the following elements;

C:
User
CoolDude
Documents
Access
Test.pdf

You could then reconstruct a string from element 3.

Bear in mind that a users working directories can be moved, like mine I never keep them on the C: drive, to another location in which case the rules would possibly change.
PIEBALDconsult 14-Jul-17 16:35pm    
Use the classes in the System.IO namespace instead.
George Swan 15-Jul-17 4:48am    
I'd use Split like this
string path = @"C:\Users\CoolDude\Documents\Access\Test.pdf";
int count = path.Count(c => c == '\\');
ArraySegment<string> splitArray=new ArraySegment<string>(path.Split('\\'),count-2,3);
string pathResult= string.Join("\\", splitArray);

1 solution

Try:
public static Regex regex = new Regex(@".:\\Users\\.+?\\", RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled);
...
string result = regex.Replace(InputText,"");

If you are going to use regular expressions, get a copy of Expresso[^] - it's free, and it examines, tests, and generates regular expressions.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900