如何从Postgres中的字符串中移除一个前导和尾随的单引号(’)。

huangapple go评论77阅读模式
英文:

how to remove one leading and trailing single quote(') from a string in Postgres

问题

I need some help removing 1 leading and 1 trailing single quote from my string in Postgres 14.

string is

'''alter table test add column col2 int[] default ''''{}'''' not null'''

desired output:

''alter table test add column col2 int[] default ''''{}'''' not null''

I've tried trim but it removes the quotes from around the curly brackets as well.

=# select trim('''alter table test add column col2 int[] default ''''{}'''' not null''');
                              btrim
------------------------------------------------------------------
 'alter table test add column col2 int[] default ''{}'' not null'
英文:

I need some help removing 1 leading and 1 trailing single quote from my string in Postgres 14.

string is

'''alter table test add column col2 int[] default ''''{}'''' not null'''

desired output:

''alter table test add column col2 int[] default ''''{}'''' not null''

I've tried trim but it removes the quotes from around the curly brackets as well.

=# select trim('''alter table test add column col2 int[] default ''''{}'''' not null''');
                              btrim
------------------------------------------------------------------
 'alter table test add column col2 int[] default ''{}'' not null'

答案1

得分: 2

可以使用正则表达式替换方法:

SELECT REGEXP_REPLACE(val, '^''|''$', '', 'g') AS output
FROM yourTable;

注意:

  • 在 SQL 字符串中,一个单引号的字面表示是两个单引号。
  • 正则表达式模式 ^''|''$ 匹配字符串开头或结尾的单引号。
  • 我们使用第四个参数 g 进行全局替换。
英文:

We can use a regex replacement here:

<!-- language: sql -->

SELECT REGEXP_REPLACE(val, &#39;^&#39;&#39;|&#39;&#39;$&#39;, &#39;&#39;, &#39;g&#39;) AS output
FROM yourTable;

Notes:

  • A literal single quote in a SQL string is represented by two single quotes.
  • The regex pattern ^&#39;&#39;|&#39;&#39;$ matches a single quote at the start or end of the string.
  • We use the g 4th parameter to do a global replacement.

答案2

得分: 0

SELECT TRIM('' FROM your_string) FROM your_table_name;

请注意有四个单引号。通过在两个单引号内部放置一个单引号来转义它。

英文:
SELECT TRIM(&#39;&#39;&#39;&#39; FROM your_string) FROM your_table_name;

Note that there are four single quotes. By putting two single quotes inside, one escape the other.

huangapple
  • 本文由 发表于 2023年6月8日 11:52:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76428508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定