使用正则表达式匹配字符串中的多个字符

时间:2017-03-17 13:07:43

标签: c# regex string

我有一个以下路径,我需要转换为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
  4. 最终字符串应该看起来像

    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是正则表达式的链接

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

你可以这样做

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

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