Replace only leading and trailing whitespace with

2019-04-13 20:59发布

问题:

I want to replace only leading and trailing white space of a string by number of underscore.

Input String

" New Folder  "

(Notes: There is one white space at front and two white spaces at the end of this string)

Output

My desire output string "_New Folder__"
(The output string has one underscore at the front and two underscore at the end.)

回答1:

One solution is using a callback:

s = Regex.Replace(s, @"^\s+|\s+$", match => match.Value.Replace(' ', '_'));

Or using lookaround (a bit trickier):

s = Regex.Replace(s, @"(?<=^\s*)\s|\s(?=\s*$)", "_");


回答2:

You may also choose a non-regex solution, but I'm not sure it's pretty:

StringBuilder sb = new StringBuilder(s);
int length = sb.Length;
for (int postion = 0; (postion < length) && (sb[postion] == ' '); postion++)
    sb[postion] = '_';
for (int postion = length - 1; (postion > 0) && (sb[postion] == ' '); postion--)
    sb[postion] = '_';
s = sb.ToString();