[ACCEPTED]-Trim whitespace from middle of string-parsing
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
or
s/\s{2,}/ /g
Edit #2: forgot 1 the /g global suffix, thanks JL
str = Regex.Replace(str, " +( |$)", "$1");
0
Perl-variants: 1) s/\s+$//; 2) s/\s+/ /g;
0
C#:
Only if you wanna trim all the white 1 spaces - at the start, end and middle.
string x = Regex.Replace(x, @"\s+", " ").Trim();
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 sed
ish 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.
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.
/(^[\s\t]+|[\s\t]+([\s\t]|$))/g replace 1 with $2 (beginning|middle/end)
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.