Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim whitespace from middle of string

Tags:

regex

parsing

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:

  1. Trims all whitespace off the end
  2. Collapses any whitespace in between words to a single space
like image 676
Chris Karcher Avatar asked Oct 19 '08 19:10

Chris Karcher


1 Answers

Substitute two or more spaces for one space:

s/  +/ /g

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.

s/\s\s+/ /g

or

s/\s{2,}/ /g

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

like image 159
sk. Avatar answered Sep 18 '22 12:09

sk.