4

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.)

2 Answers 2

4

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*$)", "_");
Sign up to request clarification or add additional context in comments.

2 Comments

Looking again, new String('_', match.Length) might be more appropriate here. Oh well.
Definitely. Not only is it more obvious what is being done, but it also has the benefit of handling other whitespace characters besides space.
1

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

1 Comment

I think I've answered too many regular expression questions, I'm sure there's a better way to do this :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.