PostgreSQL常用字符串分割函數整理匯總
1. SPLIT_PART
SPLIT_PART() 函數通過指定分隔符分割字符串,并返回第N個子串。語法:
SPLIT_PART(string, delimiter, position)
- string : 待分割的字符串
- delimiter:指定分割字符串
- position:返回第幾個字串,從1開始,該參數必須是正數。如果參數值大于分割后字符串的數量,函數返回空串。
示例:
SELECT SPLIT_PART('A,B,C', ',', 2); -- 返回B
下面我們利用該函數分割日期,獲取年月日:
select split_part( current_date::text,'-',1) as year , split_part( current_date::text,'-',2) as month, split_part( current_date::text,'-',3) as day
返回信息:
year | month | day |
---|---|---|
2021 | 09 | 11 |
2.STRING_TO_ARRAY
該函數用于分割字符串至數組元素,請看語法:
string_to_array(string, delimiter [, null string])
- string : 待分割的字符串
- delimiter:指定分割字符串
- null string : 設定空串的字符串
舉例:
SELECT string_to_array('xx~^~yy~^~zz', '~^~'); -- {xx,yy,zz} SELECT string_to_array('xx~^~yy~^~zz', '~^~', 'yy'); -- {xx,,zz}
我們也可以利用unnest函數返回表:
SELECT t as name FROM unnest(string_to_array('john,smith,jones', ',')) AS t;
name |
---|
john |
smith |
jones |
3. regexp_split_to_array
使用正則表達式分割字符串,請看語法:
regexp_split_to_array ( string text, pattern text [, flags text ] ) → text[]
請看示例:
postgres=# SELECT regexp_split_to_array('foo bar baz', '\s+'); regexp_split_to_array ----------------------- {foo,bar,baz} (1 row)
當然也有對應可以返回table的函數:
SELECT t as item FROM regexp_split_to_table('foo bar,baz', E'[\\s,]+') AS t;
返回結果:
item |
---|
foo |
bar |
baz |
4.regexp_split_to_array
select regexp_split_to_array('the,quick,brown;fox;jumps', '[,;]') AS subelements -- 返回 {the,quick,brown,fox,jumps}
于上面一樣,只是返回數組類型。
5. regexp_matches
該函數返回匹配模式的字符串數組。如果需要返回所有匹配的集合,則需要的三個參數‘g’ (g 是 global 意思)。請看示例:
select regexp_matches('hello how are you', 'h[a-z]*', 'g') as words_starting_with_h
返回結果:
words_starting_with_h |
---|
{hello} |
{how} |
如果忽略 ‘g’ 參數,則僅返回第一項。
當然我們也可以使用regexp_replace函數進行替換:
select regexp_replace('yellow submarine', 'y[a-z]*w','blue'); -- 返回結果:blue submarine
總結
到此這篇關于PostgreSQL常用字符串分割函數的文章就介紹到這了,更多相關pgsql字符串分割函數內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
postgresql的now()與Oracle的sysdate區別說明
這篇文章主要介紹了postgresql的now()與Oracle的sysdate區別說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12PostgreSQL 實現distinct關鍵字給單獨的幾列去重
這篇文章主要介紹了PostgreSQL 實現distinct關鍵字給單獨的幾列去重,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
最新評論