相关推荐recommended
PostgreSQL常用字符串分割函数整理
作者:mmseoamin日期:2023-12-13

1. SPLIT_PART

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

SPLIT_PART(string, delimiter, position)

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

    示例:SELECT SPLIT_PART('A,B,C', ',', 2); -- 返回B

    2.STRING_TO_ARRAY

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

    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,NULL,zz}

        3. regexp_split_to_array|regexp_split_to_table 

        使用正则表达式分割字符串,用来将字符串转换成格式化数据,一个是转换成数组,一个是转换成结果集表,语法:

        regexp_split_to_array ( string, pattern [, flags text ] ) → text[]

        • string : 待分割的字符串
        • pattern:正则表达式或指定分割字符串

          示例1:正则表达式 

          SELECT regexp_split_to_array('foo bar  baz', '\s+');

          示例2:指定分割字符串

          • SELECT * FROM student t WHERE regexp_split_to_array(t.subject,',') @> array['英语','中国古典文学']

            PostgreSQL常用字符串分割函数整理,第1张

            •  SELECT * FROM student t WHERE regexp_split_to_array(t.subject,',') @> regexp_split_to_array('英语','中国古典文学',',')

              PostgreSQL常用字符串分割函数整理,第2张

              regexp_split_to_table ( string, pattern [, flags text ] ) 

              • string : 待分割的字符串
              • pattern:正则表达式或指定分割字符串

                PostgreSQL常用字符串分割函数整理,第3张

                 Tips:查询具体排序的第几个的用regexp_split_to_array函数,查询是否包含的条件,则使用ARRAY_AGG与 regexp_split_to_table两个函数

                4.regexp_split_to_array

                和上面一样,只是返回数据类型,语法:

                regexp_split_to_array( string, pattern ) 

                • string : 待分割的字符串
                • pattern:正则表达式或指定分割字符串

                  示例1(单个切断):

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

                  示例2(表字段和传入字符串比较):

                  select regexp_split_to_array(subjects,',') @> regexp_split_to_array('英语,中国古典文学',',')

                  @> 包含的关系,不指定顺序

                  subjects 包含 数据:'英语','中国古典文学'

                  = 相等的关系

                  subjects 等于 数据:'英语','中国古典文学'

                  != 不等的关系

                  subjects 不等于 数据:'英语','中国古典文学'

                  && 存在

                  subjects 包含 数据:'英语','中国古典文学' 其中的一条

                   

                  5. regexp_matches

                  匹配一个POSIX正则表达式针对字符串并返回匹配的子字符串。语法:

                  REGEXP_MATCHES(string, pattern [, flags])