我需要清理一个字符串列,其中包含空格和制表符,在字符串的开头或结尾处(这很麻烦!)。我想在每个单词之间只留一个空格。假设我们有以下字符串,其中包含所有可能的情况:
mystring = ' one two three four '
这是我的方式:
WITH
t1 AS (SELECT' one two three four '::TEXT AS mystring),
t2 AS (SELECT TRIM(both ' ' from mystring) AS mystring FROM t1),
t3 AS (SELECT TRIM(both '\t' from mystring) AS mystring FROM t2)
SELECT regexp_replace(mystring, '(( ){2,}|\t+)', ' ', 'g') FROM t3 ;
我最终得到以下字符串,看起来不错,但我仍然有一个尾随空格......
'one two three four '
是否有任何想法以更简单的方式进行并解决最后一个问题?
非常感谢!
答案 0 :(得分:30)
SELECT trim(regexp_replace(col_name, '\s+', ' ', 'g')) as col_name FROM table_name;
或者在更新的情况下:
UPDATE table_name SET col_name = trim(regexp_replace(col_name, '\s+', ' ', 'g'));
答案 1 :(得分:1)
SELECT trim(regexp_replace(mystring, '\s+', ' ', 'g')) as mystring FROM t1;
如果人们不看评论,可以发布答案。
使用'\s+'
不是'\\s+'
为我工作。
答案 2 :(得分:0)
trim
和regexp_replace
对我无效。所以我提出了另一个解决方案:
SELECT trim(
array_to_string(
regexp_split_to_array(' test with many spaces for this test ', E'\\s+')
, ' ')
) as mystring;
首先regexp_split_to_array
消除所有留下空格"空白"在开始和结束。
-- regexp_split_to_array output:
-- {"",test,with,many,spaces,for,this,test,""}
当using array_to_string
所有','成为空间
-- regexp_split_to_array output ( '_' instead of spaces for viewing ):
-- _test_with_many_spaces_for_this_test_
修剪是去除头部和尾部
-- trim output ( '_' instead of spaces for viewing ):
-- test_with_many_spaces_for_this_test