删除开头、中间、结尾的空格

Remove whitespaces from beginning, between, end

我有闲置字符串 ' this is my string ' 是否可以删除开头和结尾的所有白色 space,只在单词之间留一个 space。

至 select 我用过的所有 space:

SELECT regexp_replace('   this  is my  string   ', '[ ]{2,}', '', 'g');

问题在于单词之间的两个 space。

使用锚点。

SELECT regexp_replace('   this  is my  string   ', '^ +| +$|( ) +', '', 'g');

DEMO

  • ^ + 匹配所有前导的一个或多个 space。
  • |
  • <space>+$ 匹配所有尾随 spaces.
  • | 或(即来自 remianing 字符串)
  • ( ) + 捕获第一个 space 并匹配以下所有 space。
  • 将所有匹配的 space 替换为组索引 1 将为您提供所需的输出。
SELECT 
trim(both ' ' from regexp_replace('    this  is my  string   ', '  +', ' ', 'g'));

您可以使用:

SELECT regexp_replace('   this  is my  string   ', '^ +| +$| +(?= )', '', 'g');

RegEx Demo

这将从以下位置删除所有 spaces:

  1. 开始
  2. 结束
  3. 将中间的多个 space 转换为单个 space

解释:

  • ^ +| +$ 匹配字符串开头或结尾的 spaces
  • +(?= ) 是一个积极的前瞻,匹配 1 个或多个 spaces 只有当它后面至少有一个 space
  • 替换为空字符串。