从字符串中间修剪空格 [英] Trim whitespace from middle of string

查看:88
本文介绍了从字符串中间修剪空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下正则表达式捕获始终为50个字符的固定宽度说明"字段:

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. 修剪所有空白
  2. 将单词之间的所有空格都折叠到单个空格

推荐答案

用两个或多个空格代替一个空格:

Substitute two or more spaces for one space:

s/  +/ /g

对于任何空白(不只是空格),如果您使用的是与Perl兼容的正则表达式库,则可以使用\ s,并使用大括号语法表示出现的次数,例如

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

s/\s{2,}/ /g

编辑#2:忘了/g全局后缀,谢谢JL

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

这篇关于从字符串中间修剪空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆