2

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

KevinDeus
  • 11,988
  • 20
  • 65
  • 97

4 Answers4

6

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("\\", "/"));
Jeff Meatball Yang
  • 37,839
  • 27
  • 91
  • 125
5

.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
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Rob Livermore
  • 51
  • 1
  • 1
1
^(\\\\\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 /.

Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
0

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 :)

Jeremy Smyth
  • 23,270
  • 2
  • 52
  • 65