Question

My program reads in a string list which contains both file and folder names located on a network drive.

Here are some examples of what my list can contain:

\\NETWORKDRIVE\text1.txt
\\NETWORKDRIVE\\text2.txt
\\NETWORKDRIVE\foldername\text3.txt
\\NETWORKDRIVE\\
\\NETWORKDRIVE\
\\NETWORKDRIVE

I need a regular expression to return the network drive name only (including the leading "\" characters).

I have tried various regular expressions and I have found one that almost works. Here is what I have currently:

^(\\+)(.*?)(\\+)

There are two problems with this regular expression.

The first problem is that it matches the network drive name and the trailing "\" characters. The second problem is that if the network drive name doesn't end with any "\" characters it only matches the leading "\" characters.

Here are my results to demonstrate:

\\NETWORKDRIVE\text1.txt => \\NETWORKDRIVE\
\\NETWORKDRIVE\\test2.txt => \\NETWORKDRIVE\\
\\NETWORKDRIVE\foldername\text3.txt => \\NETWORKDRIVE\
\\NETWORKDRIVE\\ => \\NETWORKDRIVE\\
\\NETWORKDRIVE\ => \\NETWORKDRIVE\
\\NETWORKDRIVE => \\

As you can see I am not getting the results that I want. I simply want the result to be:

\\NETWORKDRIVE

for all cases.

Can anyone help me modify and/or change my regular expression to do what I need it to do?

Thank you very much.

Was it helpful?

Solution

You can use this:

^\\{2}[^\\]+

[^\\] means all characters except the backslash

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top