Question

I'm looking for a nice tight regex solution to this problem. I'm looking to reformat an UNC into a Uri

Problem:

UNC directory needs to be reformatted into a Uri

\\server\d$\x\y\z\AAA

needs to look like:

http://server/z/AAA

Was it helpful?

Solution

I think a replace is easier to write and understand than Regex in this case. Given:

string input = "\\\\server\\d$\\x\\y\\z\\AAA";

You can do a double replace:

string output = String.Format("http:{0}", input.Replace("\\d$\\x\\y", String.Empty).Replace("\\", "/"));

OTHER TIPS

.Net framework supports a class called System.Uri which can do the conversion. It is simpler and handles the escape cases. It handles both UNC, local paths to Uri format.

C#:

Console.WriteLine((new System.Uri("C:\Temp\Test.xml")).AbsoluteUri);

PowerShell:

(New-Object System.Uri 'C:\Temp\Test.xml').AbsoluteUri

Output:

file:///C:/Temp/Test.xml
^(\\\\\w+)\\.*(\\\w\\\w+)$
  • First match: \\server

  • Second match: \z\AAA

Concatenate to a string and then prepend http: to get http:\\server\z\AAA. Replace \ with /.

Two operations:

  • first, replace "(.*)d\$\\x\\y\\(.*)" with "http:\1\2" - that'll clear out the d$\x\y\, and prepend the http:.

  • Then replace \\ with / to finish the job.

Job done!

Edit: I'm assuming that in C#, "\1" contains the first parenthesised match (it does in Perl). If it doesn't, then it should be clear what is meant above :)

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