在postgresql中,我需要提取给定列的值中的前两个单词。因此,如果价值是“你好世界的月亮和星星”或“你好世界的月亮”,甚至只是“你好世界”,我需要“你好世界”。
我希望使用regexp_split_to_array
,但似乎我不能使用它并访问同一查询中返回的元素?
我是否需要为我正在尝试的内容创建一个函数?
答案 0 :(得分:10)
我无法相信5年前,如果用括号括起来,没有人注意到你可以访问 regexp_split_to_array 函数中的元素。
我看到很多人试图像这样访问表格的元素:
select regexp_split_to_array(my_field, E'my_pattern')[1] from my_table
前一个会返回错误,但以下情况不会:
select (regexp_split_to_array(my_field, E'my_pattern'))[1] from my_table
答案 1 :(得分:8)
您可以将POSIX正则表达式与PostgreSQL的substring()
:
select substring('hello world moon' from E'^\\w+\\s+\\w+');
或者对一个词的含义进行非常自由的解释:
select substring('it''s a nice day' from E'^\\S+\\s+\\S+');
请注意\S
(非空白)而不是\w
(“单词”字符,基本上是字母数字加上下划线)。
不要忘记所有额外引用的废话:
E''
告诉PostgreSQL你正在使用extending escaping。如果您真的想使用regexp_split_to_array
,那么您可以,但上述引用问题适用,我认为您只想切掉数组的前两个元素:
select (regexp_split_to_array('hello world moon', E'\\s+'))[1:2];
我猜测逃跑造成了一些混乱;我通常最后添加反斜杠直到它工作,然后我挑选它,直到我理解为什么我需要我最终使用的反斜杠的数量。或许额外的括号和数组切片语法是一个问题(这对我而言,但有一些实验将其整理出来)。
答案 2 :(得分:2)
找到了一个答案:
select split_part('hello world moon', ' ', 1) || ' ' || split_part('hello world moon', ' ', 2);
答案 3 :(得分:1)
select substring(my_text from $$^\S+\s+\S+$$) from v;
substring
-------------
hello world
hello world
hello world
(3 rows)
为了演示的目的,v是:
create view v as select 'hello world moon and stars' as my_text union all
select 'hello world mood' union all
select 'hello world';
如果你想在开头忽略空格:
select substring(my_text from $$^\s*\S+\s+\S+$$) from v;