Regular Expressions ~ convert UNC to URL

岁酱吖の 提交于 2019-12-02 03:34:32

问题


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


回答1:


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("\\", "/"));



回答2:


.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



回答3:


^(\\\\\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 /.




回答4:


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



来源:https://stackoverflow.com/questions/1053300/regular-expressions-convert-unc-to-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!