文章摘要
这篇文章介绍了PostgreSQL中常用的字符串分割函数及其用途。主要包括以下函数及其应用场景:
1. **SPLIT_PART**
- 语法:`SPLIT_PART(string, delimiter, position)`
- 功能:按指定分隔符分割字符串,并返回第N个子串(从1开始计数)。
- 示例:`SELECT SPLIT_PART('A,B,C', ',', 2);` 返回 'B'。
- 用于分割日期等复杂字符串。
2. **STRING_TO_ARRAY**
- 语法:`STRING_TO_ARRAY(string, delimiter, [null_string])`
- 功能:将字符串按指定分隔符分割并返回数组。可指定空字符串作为默认值。
- 示例:`SELECT STRING_TO_ARRAY('xx~^~yy~^~zz', '~^~');` 返回 `{xx, yy, zz}`。
- 与`unnest`结合使用,返回表。
3. **regexp_split_to_array**
- 语法:`regexp_split_to_array(string text, pattern text, [flags text])`
- 功能:使用正则表达式分割字符串,并返回匹配结果。可指定返回数组类型。
- 示例:`SELECT regexp_split_to_array('foo bar baz', 's+');` 返回 `{foo, bar, baz}`。
- 与`regexp_split_to_array`配合使用,返回数组。
4. **regexp_matches**
- 语法:`regexp_matches(string text, pattern text, [flags text])`
- 功能:返回所有匹配的模式结果。若使用全局参数,可获取全部匹配结果。
- 示例:`SELECT regexp_matches('hello how are you', 'h[a-z]*', 'g') AS words_starting_with_h;` 返回 `{hello, how}`。
- 用于提取特定模式的字符串。
总结:这篇文章详细介绍了PostgreSQL中用于字符串分割的四个函数,包括`SPLIT_PART`、`STRING_TO_ARRAY`、`regexp_split_to_array`和`regexp_matches`。它们在处理字符串分割和模式匹配方面各有特点,适用于多种数据处理场景。
目录1. SPLIT_PART2.STRING_TO_ARRAY3. regexp_split_to_array4.regexp_split_to_array5. regexp_matches总结
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
返回信息:
yearmonthday20210911
该函数用于分割字符串至数组元素,请看语法:
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;
namejohnsmithjones
使用正则表达式分割字符串,请看语法:
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;
返回结果:
itemfoobarbaz
select regexp_split_to_array(‘the,quick,brown;fox;jumps’, ‘[,;]’) AS subelements
— 返回 {the,quick,brown,fox,jumps}
于上面一样,只是返回数组类型。
该函数返回匹配模式的字符串数组。如果需要返回所有匹配的集合,则需要的三个参数‘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 实现字符串分割字段转列表查询