I'm using the following regex to capture a fixed width "description" field that is always 50 characters long:
(?.{50})
My problem is that the descriptions sometimes contain a lot of whitespace, e.g.
"FLUID COMPRESSOR "
Can somebody provide a regex that:
- Trims all whitespace off the end
- Collapses any whitespace in between words to a single space
Perl-variants: 1) s/\s+$//; 2) s/\s+/ /g;
Since compressing whitespace and trimming whitespace around the edges are conceptually different operations, I like doing it in two steps:
Not the most efficient, but quite readable.
C#:
Only if you wanna trim all the white spaces - at the start, end and middle.
Substitute two or more spaces for one space:
Edit: for any white space (not just spaces) you can use \s if you're using a perl-compatible regex library, and the curly brace syntax for number of occurrences, e.g.
or
Edit #2: forgot the /g global suffix, thanks JL
/(^[\s\t]+|[\s\t]+([\s\t]|$))/g replace with $2 (beginning|middle/end)
Is there a particular reason you are asking for a regular expression? They may not be the best tool for this task.
A replacement like
should compress the internal whitespace (actually, it will compress leading and trailing whitespace too, but it doesn't sound like that is a problem.), and
will take care of the trailing whitespace. [I'm using
sed
ish syntax here. You didn't say what flavor you prefer.]Right off hand I don't see a way to do it in a single expression.