2016-12-02 68 views
0

我有與具有串這樣的字段的表:訪問第二元件在regexp_matches陣列

US 19; PA 65

我需要拆分此伸到等4個新字段:

'美國','19' , 'PA', '65'

REG exp_matches似乎是票。我可以用以下語句將'US'提取到一個字段中,並將'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訪問第二個匹配項?

+0

'選擇regexp_matches( 'US 19; PA 65',「([[:阿爾法:]] + )\ S *([[:數字:]] +);([[:阿爾法:]] +)\ S *([[:位:]])+');' – Abelisto

回答

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)