所以我有一列带有以下值的列,有时在开头有一个数字
turtle boat
10 banana split
lord Thanos
23 macbook
如何查询删除数字和数字前面的空格,而不是删除字符串中间的空格?
预期输出:
turtle boat
banana split
lord Thanos
macbook
我在这里尝试过另一个问题的查询:
select regexp_replace(mycolumn, '[^[:alpha:]]', '', 'g')
此查询的问题是它会完全删除所有空格
答案 0 :(得分:3)
这将删除前导数字和空格:
select regexp_replace('10 banana split', '^\d+ ', '');
/^\d+[ ]/
^ asserts position at start of a line
\d+ matches a digit (equal to [0-9])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
[ ] matches the character ' ' literally (case sensitive)
g
修饰符,表示“全局”,这就是为什么在正则表达式中所有空格都被删除了,与非字母字符匹配的原因。
提琴here
答案 1 :(得分:2)
您可以排除字母和空格以外的所有字符。另外,使用trim()
删除前导或尾随空格:
with my_data(mycolumn) as (
values
('turtle boat'),
('10 banana split'),
('lord Thanos'),
('23 macbook')
)
select trim(regexp_replace(mycolumn, '[^[:alpha:]\s]', '', 'g'))
from my_data
btrim
--------------
turtle boat
banana split
lord Thanos
macbook
(4 rows)