简体   繁体   中英

postgresql 9.5: trying to split a string into two fields based on spaces

I have a field in a postgres table that looks like the table below. I want to split the string into two separate components based upon the space as a delimiter. Note all of the fields are TEXT.

 tablename:  intersection_table_wi
 wwhid   
 -----   

 "102  5" 
 "104 61"
 "103 84"

So I want to convert this to a Target like this:

 wwhid     wv002     wv003
 -----     -----     -----

 "102  5"  "102"     "5"
 "104 61"  "104"     "61"
 "103 84"  "103"     "84"

The problem is that when I write the query I keep getting things that look more like this:

 wwhid     wv002     wv003
 -----     -----     -----

 "102  5"  "102  5"   ""
 "104 61"  "104 61"   ""
 "103 84"  "103 84"   ""

Now the subtle problem is that in some cases there is more than one space between the two substrings in whhid while in other cases there is only one space.

The query I tried are as follow:

UPDATE intersection_table_wi 
SET wv002 = SPLIT_PART(BTRIM(whhid), '/\s+', 1), 
wv003 = SPLIT_PART(BTRIM(whhid), '/\s+', 2);

Can anyone tell me how I can fix this query to obtain the target specified above?

split_part() doesn't support regular expressions. You can only specify a "simple" string as the delimiter.

To split on a regular expression you need regexp_split_to_array()

UPDATE intersection_table_wi 
   SET wv002 = (regexp_split_to_array(BTRIM(whhid), '\s+'))[1], 
       wv003 = (regexp_split_to_array(BTRIM(whhid), '\s+'))[2];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM