简体   繁体   中英

C# find and replace

I have a string variable of type ////abc/abc/abc/asd.aspx .

There can be any number of / at the begining of a string, i want the output to be /abc/abc/abc/asd.aspx .

There can also be a string value as /abc/abc/abc/asd.aspx whose output should emain as /abc/abc/abc/asd.aspx

Kindly help, how do i use String.Replace(); or any other method i can use?

You can do something like this:

var correctedString = "/" + originalString.TrimStart('/');

Or you van do it via RegEx if there are any number of / in any part of string:

var correctedString = Regex.Replace(originalString, "/{2,}", "/");
string str = " ////abc/abc/abc/asd.aspx";
string newStr = "/"  + string.Join("/", str.Split(new[] { "/" }, 
                                        StringSplitOptions.RemoveEmptyEntries));

This would work for string like "///abc///abc//abc/asd.aspx" as well.

You can use Regular Expressions:

string path = "////abc/abc/abc/asd.aspx";

path = System.Text.RegularExpressions.Regex.Replace(path, @"/+", "/");

Result:

/abc/abc/abc/asd.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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