Trim whitespace from middle of string

2019-04-20 02:29发布

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

标签: regex parsing
7条回答
Emotional °昔
2楼-- · 2019-04-20 03:01

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

查看更多
叼着烟拽天下
3楼-- · 2019-04-20 03:03

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

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

Not the most efficient, but quite readable.

查看更多
在下西门庆
4楼-- · 2019-04-20 03:06

C#:

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

     string x = Regex.Replace(x, @"\s+", " ").Trim();
查看更多
我命由我不由天
5楼-- · 2019-04-20 03:14

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

查看更多
等我变得足够好
6楼-- · 2019-04-20 03:14

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

查看更多
家丑人穷心不美
7楼-- · 2019-04-20 03:15

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

 s/[ \t]+/ /g

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

s/[ \t]+$/$/

will take care of the trailing whitespace. [I'm using sedish 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.

查看更多
登录 后发表回答