简体   繁体   English

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

[英]Matching multiple chars in string using regex

I have a the following path which I need to convert to URL. 我有以下路径,需要将其转换为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 an https added at the front ie https://` \\\\ will become // with an added at the front ie with an https added at the front ie https://`
  2. \\ will become / \\将成为/
  3. User_Attachments$ will become User_Attachments User_Attachments$将成为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 为此,我提出了以下regex

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

I then match using the Matches() method as: 然后,我使用Matches()方法进行Matches()

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. 我的问题是如何检查匹配是否成功,并在适当的组中替换适当的值,并具有如上所述的最终url字符串。

Here is the link to the regex 是正则表达式的链接

As mentioned above, i'd go for a simple Replace : 如上所述,我将进行简单的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? 例如,从以下这些SO答案之一中取出如何从字符串中删除除破折号以外的所有非字母数字字符?

// 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);

You can do it like this 你可以这样

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM