我正在使用Postgres尝试在返回字符串之前截断它,以便可以在客户端部分结果列表中显示。关键是它需要以完整的单词结尾。我已经做到了这一点:
SELECT comments, substr(comments, 1, 80) AS "trunc" FROM book;
下一步应该是对子字符串进行正则表达式的子字符串操作(也许要确保字符串以空格结尾)吗?
我正在使用Postgres尝试在返回字符串之前截断它,以便可以在客户端部分结果列表中显示。关键是它需要以完整的单词结尾。我已经做到了这一点:
SELECT comments, substr(comments, 1, 80) AS "trunc" FROM book;
下一步应该是对子字符串进行正则表达式的子字符串操作(也许要确保字符串以空格结尾)吗?
substring(string from pattern)
函数。示例:提取12个字符。with the_data(comments) as (
values
('follow me'::text),
('abcdef ghijkl'),
('abcd efgh ijkl'),
('abc def ghi jkl'),
('ab cd ef gh ij kl')
)
select substring(left(comments || ' ', 12) from '.*\s')
from the_data;
substring
--------------
follow me
abcdef
abcd efgh
abc def ghi
ab cd ef gh
(5 rows)
('follow me'::text)
- 它会截断 'me',但我对 OPs 问题的解释是它应该返回 'follow me'(在此示例中)。 - Nickselect substring(left(comments || ' ', 12) from '.*\s') from the_data;
- Nick