日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

PostgreSQL常用字符串分割函數(shù)整理匯總_PostgreSQL

作者:夢想畫家 ? 更新時間: 2022-08-28 編程語言

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 : 設定空串的字符串

舉例:

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

使用正則表達式分割字符串,請看語法:

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的函數(shù):

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}

于上面一樣,只是返回數(shù)組類型。

5. regexp_matches

該函數(shù)返回匹配模式的字符串數(shù)組。如果需要返回所有匹配的集合,則需要的三個參數(shù)‘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’ 參數(shù),則僅返回第一項。

當然我們也可以使用regexp_replace函數(shù)進行替換:

select regexp_replace('yellow submarine', 'y[a-z]*w','blue');
-- 返回結果:blue submarine

總結

原文鏈接:https://blog.csdn.net/neweastsun/article/details/120243524

欄目分類
最近更新