2017-03-17 32 views
0

我有我需要转换为URL的以下路径。使用正则表达式在字符串中匹配多个字符

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

我试图替换替换此字符串中的特殊字符。所以

  1. \\ will become // with an HTTPS added at the front i.e. https://开头`
  2. \将成为/
  3. User_Attachments$将成为User_Attachments

最终的字符串应该像

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

要做到这一点,我想出了以下regex

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

我再搭配使用Matches()方法:

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

我的问题是我怎么能检查,看看是否匹配是成功并在相应的组中取代适当的值,然后如上所述获得最终的url字符串。

Here是链接到正则表达式

+3

你为什么要用正则表达式来做呢?一个简单的'string.Replace()'链接就足够了,并允许更好的可读性的最终代码... – zaitsman

+0

@zaitsman我不必使用正则表达式,我只是不知道如何使用字符串替换多个值.Replace()'因此我沿着这条路线走了。如果你可以提供一个例子 – Code

回答

3

正如上面提到的,我会去一个简单的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 

例如,从这些SO答案中取出: 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); 
+0

你让它看起来很容易:/你可以详细说明你的评论请 – Code

+0

你想要以确保URL是编码的,你也应该使用HttpServerUtility.UrlEncode来确保任何特殊字符 –

+0

请参阅更新的答案 - >你可以使用类似的东西 – zaitsman

0

你可以像下面这样做

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

string actualUrl=path.Replace("\\","https://").Replace("\","/") 
+0

你错过了'$':) – zaitsman

+0

:D这就是为什么我给了你投票 –