0

I have a the following path which I need to convert to URL.

string path = @"\\TestServer\User_Attachments$\Data\Reference\Input\Test.png";

I'm trying to replace the replace the special chars in this string. So

  1. \\ will become//with anhttpsadded at the front i.e.https://`
  2. \ will become /
  3. User_Attachments$ will become User_Attachments

The final string should look like

string url = "https://TestServer/User_Attachments/Data/Reference/Input/Test.png"

To achieve this I've come up with the following regex

string pattern = @"^(.{2})|(\\{1})|(\${1})";

I then match using the Matches() method as:

var match = Regex.Matches(path, pattern);

My question is how can I check to see if the match is success and replace the appropriate value at the appropriate group and have a final url string as I mentioned above.

Here is the link to the regex

Izzy
  • 6,740
  • 7
  • 40
  • 84
  • 3
    Why do you want to do it with regex? a simple `string.Replace()` chained would suffice and allow for greater readability of the final code... – zaitsman Mar 17 '17 at 13:09
  • @zaitsman I don't have to use regex, I just didn't know how to replace multiple values using `string.Replace()` hence why I went down this route. Would it be possible if you can provide an example please – Izzy Mar 17 '17 at 13:10

2 Answers2

3

As mentioned above, i'd go for a simple Replace:

string path = @"\\TestServer\User_Attachments$\Data\Reference\Input\Test.png";
var url = path.Replace(@"\\", @"https://").Replace(@"\", @"/").Replace("$", string.Empty); 
// note if you want to get rid of all special chars you would do the last bit differently

For example, taken out of one of these SO answers here: How do I remove all non alphanumeric characters from a string except dash?

// assume str contains the data with special chars

char[] arr = str.ToCharArray();

arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c) 
                                  || char.IsWhiteSpace(c) 
                                  || c == '-'
                                  || c == '_')));
str = new string(arr);
Community
  • 1
  • 1
zaitsman
  • 8,984
  • 6
  • 47
  • 79
0

You can do it like this

string path = @"\\TestServer\User_Attachments$\Data\Reference\Input\Test.png";

string actualUrl=path.Replace("\\","https://").Replace("\","/")
Ammar Ahmed
  • 126
  • 8