[ACCEPTED]-Trim whitespace from middle of string-parsing

Accepted answer
Score: 15

Substitute two or more spaces for one space:

s/  +/ /g

Edit: for 5 any white space (not just spaces) you can 4 use \s if you're using a perl-compatible 3 regex library, and the curly brace syntax 2 for number of occurrences, e.g.

s/\s\s+/ /g


s/\s{2,}/ /g

Edit #2: forgot 1 the /g global suffix, thanks JL

Score: 9
str = Regex.Replace(str, " +( |$)", "$1");


Score: 2

Perl-variants: 1) s/\s+$//; 2) s/\s+/ /g;


Score: 2


Only if you wanna trim all the white 1 spaces - at the start, end and middle.

     string x = Regex.Replace(x, @"\s+", " ").Trim();
Score: 1

Is there a particular reason you are asking 10 for a regular expression? They may not be 9 the best tool for this task.

A replacement 8 like

 s/[ \t]+/ /g

should compress the internal whitespace 7 (actually, it will compress leading and 6 trailing whitespace too, but it doesn't 5 sound like that is a problem.), and

s/[ \t]+$/$/

will 4 take care of the trailing whitespace. [I'm 3 using sedish syntax here. You didn't say what 2 flavor you prefer.]

Right off hand I don't 1 see a way to do it in a single expression.

Score: 1

Since compressing whitespace and trimming 4 whitespace around the edges are conceptually 3 different operations, I like doing it in 2 two steps:

re.replace("s/\s+/ /g", str.strip())

Not the most efficient, but quite 1 readable.

Score: 0

/(^[\s\t]+|[\s\t]+([\s\t]|$))/g replace 1 with $2 (beginning|middle/end)

More Related questions