2017-03-17 59 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這就是爲什麼我給了你投票 –