首页 > 解决方案 > 使用postgres进行字符串操作,如何删除第一个位置的字符(如果存在)

问题描述

我正在尝试在 postgres 中转换字符串以标准化我的字符串。

我有两个小问题。

  1. 例如,我有字符串

     APARTMENT IN
     RESIDENCE OF
     campsite of the
     _beach of_
    

我已经想标准化空格之间的每个单词都是小写的,并且第一个字母是大写的

  Apptment In
    Residence Of
    Camping Of The
Beach Of
  1. 有时我在字符串的开头和结尾都有 _,如果第一个和最后一个位置有 _,我想删除它们。

感谢您

标签: sqlpostgresql

解决方案


这可能会 - 拆分为单词数组,initcap用于大写单词并regexp_replace删除下划线,最后再次合并为单个字符串。

select string_agg(s, ' ') from
(
 select initcap(regexp_replace(unnest(regexp_split_to_array(trim(
' APARTMENT IN RESIDENCE OF 
 campsite of the
 _beach of_'), '\s+', 'x')), '_?([a-zA-Z]+)_?', '\1'))
) t(s);

-- result: Apartment In Residence Of Campsite Of The Beach Of

编辑 - 确保词序不会改变

select string_agg(initcap(regexp_replace(w, '_?([a-zA-Z]+)_?', '\1')), ' ')
from 
(
 select w 
 from unnest(regexp_split_to_array(trim(
' APARTMENT IN RESIDENCE OF 
campsite of the
_beach of_'), '\s+', 'x')) with ordinality t(w, o)
 order by o
) t;

推荐阅读