PostgreSQL常用字符串分割函數(shù)整理匯總
1. SPLIT_PART
SPLIT_PART() 函數(shù)通過指定分隔符分割字符串,并返回第N個子串。語法:
SPLIT_PART(string, delimiter, position)
- string : 待分割的字符串
- delimiter:指定分割字符串
- position:返回第幾個字串,從1開始,該參數(shù)必須是正數(shù)。如果參數(shù)值大于分割后字符串的數(shù)量,函數(shù)返回空串。
示例:
SELECT SPLIT_PART('A,B,C', ',', 2); -- 返回B
下面我們利用該函數(shù)分割日期,獲取年月日:
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
該函數(shù)用于分割字符串至數(shù)組元素,請看語法:
string_to_array(string, delimiter [, null string])
- string : 待分割的字符串
- delimiter:指定分割字符串
- null string : 設(shè)定空串的字符串
舉例:
SELECT string_to_array('xx~^~yy~^~zz', '~^~'); -- {xx,yy,zz} SELECT string_to_array('xx~^~yy~^~zz', '~^~', 'yy'); -- {xx,,zz}
我們也可以利用unnest函數(shù)返回表:
SELECT t as name FROM unnest(string_to_array('john,smith,jones', ',')) AS t;
name |
---|
john |
smith |
jones |
3. regexp_split_to_array
使用正則表達(dá)式分割字符串,請看語法:
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)
當(dāng)然也有對應(yīng)可以返回table的函數(shù):
SELECT t as item FROM regexp_split_to_table('foo bar,baz', E'[\\s,]+') AS t;
返回結(jié)果:
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}
于上面一樣,只是返回數(shù)組類型。
5. regexp_matches
該函數(shù)返回匹配模式的字符串?dāng)?shù)組。如果需要返回所有匹配的集合,則需要的三個參數(shù)‘g’ (g 是 global 意思)。請看示例:
select regexp_matches('hello how are you', 'h[a-z]*', 'g') as words_starting_with_h
返回結(jié)果:
words_starting_with_h |
---|
{hello} |
{how} |
如果忽略 ‘g’ 參數(shù),則僅返回第一項。
當(dāng)然我們也可以使用regexp_replace函數(shù)進(jìn)行替換:
select regexp_replace('yellow submarine', 'y[a-z]*w','blue'); -- 返回結(jié)果:blue submarine
總結(jié)
到此這篇關(guān)于PostgreSQL常用字符串分割函數(shù)的文章就介紹到這了,更多相關(guān)pgsql字符串分割函數(shù)內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。