【问题标题】:Search for string that start or finish with spaces and removing these spaces搜索以空格开头或结尾的字符串并删除这些空格
【发布时间】:2021-04-25 03:50:27
【问题描述】:

我有一个表格,其中某些列有空格,如下所示:

Column A
-----------
"text 1"
" text 2"
"text 3 "
" text 4 "

我想做一个 select 来返回那些带有空格的列(开始或结束)

" text 2"
"text 3 "
" text 4 "

这可能吗?

搜索它们后,如何更新这些列以删除空格?

【问题讨论】:

标签: postgresql


【解决方案1】:

我会使用btrim():

select column_a
  from your_table
 where btrim(column_a) != column_a;

【讨论】:

    【解决方案2】:

    我用 REGEX 解决了我的问题:

    select column_a
      from your_table
     where column_a ~* '(^\s+)*(\s+$)';
    

    trim 的问题在于它只删除带有 unicode U+0020 的空格。 TABS 和其他人不会被抓到。

    并更新列:

    UPDATE mytable
       SET col_a = substring(col_a, '\S(?:.*\S)*')
     WHERE col_a in (
        select col_a from mytable
         where col_a ~* '^\s+|\s+$'
    );
    

    【讨论】:

    • 正则表达式很昂贵。使用来自 bruno caballo 的评论。
    • @fukanchik 我同意你的看法。但是trim 不能按我想要的方式工作,解释在这里:stackoverflow.com/a/22701212/9033414 如果不使用trim,另一种方式是substring
    猜你喜欢
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 2011-03-23
    • 2016-08-05
    • 2021-12-29
    • 1970-01-01
    • 2013-10-07
    • 2021-07-04
    相关资源
    最近更新 更多