sql - 使用postgres进行字符串操作,如何删除第一个位置的字符(如果存在)
问题描述
我正在尝试在 postgres 中转换字符串以标准化我的字符串。
我有两个小问题。
例如,我有字符串
APARTMENT IN RESIDENCE OF campsite of the _beach of_
我已经想标准化空格之间的每个单词都是小写的,并且第一个字母是大写的
Apptment In
Residence Of
Camping Of The
Beach Of
- 有时我在字符串的开头和结尾都有 _,如果第一个和最后一个位置有 _,我想删除它们。
感谢您
解决方案
这可能会 - 拆分为单词数组,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;
推荐阅读
- javascript - Angular-10 你必须传入一个 NgModule 或 NgModuleFactory 才能被引导
- python - 如何处理 Python 中的环境变量?
- ios - 带有工具栏但没有文本字段的 UIDatePicker
- matlab - Matlab 从 .fig 格式的子图中提取图像
- json - Python/JSON - 如何从 JSON API 中选择特定值,就像在这种情况下,我想选择“权重”为最大值的配置文件
- c++ - 在 C++ 中使用回调
- javascript - 如何在 jquery.validation 中使用另一个属性而不是 name 属性?
- php - 停用特定用户角色的 wordpress 插件
- java - Java中的信号量和调度程序竞争条件
- c++ - 为什么编译器试图将 char * 转换为 char?