当前位置:

PostgreSQL 常用字符串分割函数

访客 2024-01-05 1294 0

1.SPLIT_PART

SPLIT_PART()函数通过指定分隔符分割字符串,并返回第N个子串。语法:

SPLIT_PART(string,delimiter,position)
  • string:待分割的字符串
  • delimiter:指定分割字符串
  • position:返回第几个字串,从1开始,该参数必须是正数。如果参数值大于分割后字符串的数量,函数返回空串。

示例:

SELECTSPLIT_PART('A,B,C',',',2);--返回B

下面我们利用该函数分割日期,获取年月日:

selectsplit_part(current_date::text,'-',1)asyear,split_part(current_date::text,'-',2)asmonth,split_part(current_date::text,'-',3)asday

返回信息:

yearmonthday
20210911

2.STRING_TO_ARRAY

该函数用于分割字符串至数组元素,请看语法:

string_to_array(string,delimiter[,nullstring])
  • string:待分割的字符串
  • delimiter:指定分割字符串
  • nullstring:设定空串的字符串

举例:

SELECTstring_to_array('xx~^~yy~^~zz','~^~');--{xx,yy,zz}SELECTstring_to_array('xx~^~yy~^~zz','~^~','yy');--{xx,,zz}

我们也可以利用unnest函数返回表:

SELECTtasnameFROMunnest(string_to_array('john,smith,jones',','))ASt;
name
john
smith
jones

3.regexp_split_to_array

使用正则表达式分割字符串,请看语法:

regexp_split_to_array(stringtext,patterntext[,flagstext])→text[]

请看示例:

postgres=#SELECTregexp_split_to_array('foobarbaz','\s');regexp_split_to_array-----------------------{foo,bar,baz}(1row)

当然也有对应可以返回table的函数:

SELECTtasitemFROMregexp_split_to_table('foobar,baz',E'[\\s,]')ASt;

返回结果:

item
foo
bar
baz

4.regexp_split_to_array

selectregexp_split_to_array('the,quick,brown;fox;jumps','[,;]')ASsubelements--返回{the,quick,brown,fox,jumps}

于上面一样,只是返回数组类型。

5.regexp_matches

该函数返回匹配模式的字符串数组。如果需要返回所有匹配的集合,则需要的三个参数‘g’(g是global意思)。请看示例:

selectregexp_matches('hellohowareyou','h[a-z]*','g')aswords_starting_with_h

返回结果:

words_starting_with_h
{hello}
{how}

如果忽略‘g’参数,则仅返回第一项。

当然我们也可以使用regexp_replace函数进行替换:

selectregexp_replace('yellowsubmarine','y[a-z]*w','blue');--返回结果:bluesubmarine

发表评论

  • 评论列表
还没有人评论,快来抢沙发吧~