访问regexp_matches数组中的第二个元素

时间:2016-12-02 18:21:41

标签: regex postgresql

我有一个表格,其字段的字符串如下:

  

US 19; PA 65

我需要将其拆分为四个新字段,例如:

  

'美国' 19',' PA',' 65'

regexp_matches似乎是票。我可以使用以下语句来提取美国'进入一个领域和' 19'到另一个。

UPDATE osm_motorway SET shieldcl1 = (regexp_matches(ref, '^[A-Z]+', 'i'))[1];

UPDATE osm_motorway SET shieldlbl1 = (regexp_matches(ref, '\d+', 'i'))[1];

但是我无法获得' PA'和' 65'用以下内容进入自己的领域。他们返回空:

UPDATE osm_motorway SET shieldcl2 = (regexp_matches(ref, '^[A-Z]+', 'i'))[2];

UPDATE osm_motorway SET shieldlbl2 = (regexp_matches(ref, '\d+', 'i'))[2];

如何使用regexp_matches访问第二个匹配项?

1 个答案:

答案 0 :(得分:1)

在另一种情况下使用这两种模式并使用标记' g'全局搜索一次获得所有匹配:

select regexp_matches('US 19;PA 65', '[A-Z]+|\d+', 'ig');

 regexp_matches 
----------------
 {US}
 {19}
 {PA}
 {65}
(4 rows)

使用此查询将结果转换为数组:

select array(select (regexp_matches('US 19;PA 65', '[A-Z]+|\d+', 'ig'))[1]);

     array     
---------------
 {US,19,PA,65}
(1 row) 

为方便起见创建功能:

create or replace function split_ref(ref text)
returns text[] language sql as $$
    select array(select (regexp_matches(ref, '[A-Z]+|\d+', 'ig'))[1])
$$;

并在更新语句中使用它:

update osm_motorway
set 
    shieldcl1  = (split_ref(ref))[1],
    shieldlbl1 = (split_ref(ref))[2],
    shieldcl2  = (split_ref(ref))[3],
    shieldlbl2 = (split_ref(ref))[4];

分割字符串的另一种方法(不使用正则表达式):

select string_to_array(translate('US 19;PA 65', ' ', ';'), ';');

 string_to_array 
-----------------
 {US,19,PA,65}
(1 row)