PostgreSQL 常⽤字符串分割函数
submarine1. SPLIT_PART SPLIT_PART() 函数通过指定分割字符串,并返回第N个⼦串。语法:string : 待分割的字符串delimiter:指定分割字符串
position:返回第⼏个字串,从1开始,该参数必须是正数。如果参数值⼤于分割后字符串的数量,函数返回空串。⽰例:
下⾯我们利⽤该函数分割⽇期,获取年⽉⽇:
返回信息:
year
month day 20210911
2.STRING_TO_ARRAY 该函数⽤于分割⾄数组元素,请看语法:string : 待分割的字符串delimiter:指定分割字符串
null string : 设定空串的字符串
举例:
我们也可以利⽤unnest函数返回表:
name
john
smith
jones SPLIT_PART (string , delimiter , position )
1SELECT  SPLIT_PART ('A,B,C', ',', 2);  -- 返回B
1select  split_part ( current_date ::text ,'-',1) as  year  ,      split_part ( current_date ::text ,'-',2) as  month ,      split_part ( current_date ::text ,'-',3) as  day
1
2
3string_to_array (string , delimiter  [, null  string ])1SELECT  string_to_array ('xx~^~yy~^~zz', '~^~');      -- {xx,yy,zz}SELECT  string_to_array ('xx~^~yy~^~zz', '~^~', 'yy'); -- {xx,,zz}
1
2SELECT  t as  name FROM  unnest (string_to_array ('john,smith,jones', ',')) AS  t ;
1
2
3. regexp_split_to_array
使⽤正则表达式分割字符串,请看语法:
请看⽰例:
当然也有对应可以返回table的函数:
返回结果:
item
foo
bar
baz
于上⾯⼀样,只是返回数组类型。
5. regexp_matches
该函数返回匹配模式的字符串数组。如果需要返回所有匹配的集合,则需要的三个参数‘g’ (g 是 global 意思)。请看⽰例:返回结果:
words_starting_with_h
{hello}
{how}
如果忽略 ‘g’ 参数,则仅返回第⼀项。
当然我们也可以使⽤regexp_replace函数进⾏替换:regexp_split_to_array ( string text , pattern text  [, flags text  ] ) → text []1postgres =# SELECT regexp_split_to_array('foo  bar baz', '\s+'); regexp_split_to_array ----------------------- {foo ,bar ,baz}(1 row )
1
2
3
4
5SELECT t as item FROM regexp_split_to_table('foo    bar,baz', E'[\\s,]+') AS t;
1
2select  regexp_split_to_array ('the,quick,brown;fox;jumps', '[,;]') AS  subelements -- 返回 {the,quick,brown,fox,jumps}1
2select  regexp_matches ('hello how are you', 'h[a-z]*', 'g')  as  words_starting_with_h
1
2select  regexp_replace ('yellow submarine', 'y[a-z]*w','blue');-- 返回结果:blue submarine 1
2