如何从 Postgres 中的字符串中删除 '\t'、'\n' 或多余的空格?
Posted
技术标签:
【中文标题】如何从 Postgres 中的字符串中删除 \'\\t\'、\'\\n\' 或多余的空格?【英文标题】:How to remove '\t', '\n' or extra spaces from a string in Postgres?如何从 Postgres 中的字符串中删除 '\t'、'\n' 或多余的空格? 【发布时间】:2020-08-06 11:45:42 【问题描述】:我在 Postgres 中有一个包含以下列的表格:
col1
The study was terminated early by the sponsor on 13 January 2014 due to a decision to modify the drug development plan.
Due to positive preliminary results from other palifermin studies.
Asset terminated by PIB
Inconsistent training status of sniffer dogs
This study was terminated early due to poor recruitment
The study was terminated due to lack of recruitment.
The scientific director decided to terminate: low priority study with slow accrual
See Termination Reason in Detailed Description.
Investigator moved to new institution
This study was terminated for administrative reasons
The app was not completed in time to conduct a clinical trial on it within the funding grant's award period
字符串中有前导和后置空格,中间有 '\n' 或 '\t'。我尝试了以下查询,但似乎没有任何结果。
select btrim(col1, '\s') from table;
update table
SET col1 = upper(substring(REGEXP_REPLACE(col1, '(\s+)', '') from 1 for 1)) || lower(substring(REGEXP_REPLACE(why_stopped, '(\s+)', '') from 2));
update table
set col1= regexp_replace(col1, E'[\\n\\r\\f\\u000B\\u0085\\u2028\\u2029]+', ' ', 'g' );
select distinct replace( replace( replace( col1, E'\n', '\n' ), E'\t', '\t' ), E'\r', '\r' )
from table;
这里的任何建议都会很有帮助。
【问题讨论】:
【参考方案1】:要在字符串文字中使用反斜杠转义,您必须在它们前面加上 E
;见the documentation。
所以试试
btrim(col1, E' \t\n')
【讨论】:
【参考方案2】:你可以使用 trim() 函数SQL String Functions and Operators
TRIM([LEADING | TRAILING | BOTH] [characters] FROM string)
你可以在这里找到例子:
postgresql-trim-function trim function
【讨论】:
【参考方案3】:我通过以下方式解决了问题:
regexp_replace(why_stopped, '\s2,', ' ', 'g')
【讨论】:
以上是关于如何从 Postgres 中的字符串中删除 '\t'、'\n' 或多余的空格?的主要内容,如果未能解决你的问题,请参考以下文章