How do I replace multiple spaces with a single space in C#?

前端 未结 24 1413
面向向阳花
面向向阳花 2020-11-22 06:37

How can I replace multiple spaces in a string with only one space in C#?

Example:

1 2 3  4    5

would be:

1 2 3 4 5         


        
24条回答
  •  名媛妹妹
    2020-11-22 07:17

    I know this is pretty old, but ran across this while trying to accomplish almost the same thing. Found this solution in RegEx Buddy. This pattern will replace all double spaces with single spaces and also trim leading and trailing spaces.

    pattern: (?m:^ +| +$|( ){2,})
    replacement: $1
    

    Its a little difficult to read since we're dealing with empty space, so here it is again with the "spaces" replaced with a "_".

    pattern: (?m:^_+|_+$|(_){2,})  <-- don't use this, just for illustration.
    

    The "(?m:" construct enables the "multi-line" option. I generally like to include whatever options I can within the pattern itself so it is more self contained.

提交回复
热议问题