Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string after every nth character

Is there a way how to split string after every nth character in PostgreSQL? I thought regexp_split_to_array can be used to do this:

select unnest(regexp_split_to_array('abcdefgh', E'...regexp here...'));

Example input: abcdefgh

Required output (split after every 2nd character):

ab
cd
ef
gh

Required output (split after every 3rd character):

abc
def
gh

What regexp will do this? Is there any other solution?

like image 463
Tomas Greif Avatar asked Jan 02 '14 21:01

Tomas Greif


People also ask

How do you split a string after a character?

To split a string at a specific character, you can use the split() method on the string and then pass that character as an argument to the split() method in JavaScript.

How can I split a string into segments of N characters in Java?

Using the String#split Method<=\\G. {” + n + “}) where n is the number of characters.

How do you split every element in a string Python?

In Python, we have an in-built method called list() to split the strings into a sequence of characters.

Can a string be split on multiple characters?

Use the String. split() method to split a string with multiple separators, e.g. str. split(/[-_]+/) . The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.


1 Answers

Use substring and generate_series:

regress=> select substring('abcdefgh' from n for 2) from generate_series(1, length( 'abcdefgh' ), 2) n;
 substring 
-----------
 ab
 cd
 ef
 gh
(4 rows)

regress=> select substring('abcdefgh' from n for 3) from generate_series(1, length( 'abcdefgh' ), 3) n;
 substring 
-----------
 abc
 def
 gh
(3 rows)

This is trivially wrapped into an inlineable SQL function:

CREATE OR REPLACE FUNCTION string_nchars(text, integer) RETURNS setof text AS $$
SELECT substring($1 from n for $2) FROM generate_series(1, length($1), $2) n;
$$ LANGUAGE sql IMMUTABLE;

Usage:

regress=> SELECT string_nchars('abcdefgh',3);
 string_nchars 
---------------
 abc
 def
 gh
(3 rows)
like image 81
Craig Ringer Avatar answered Oct 03 '22 18:10

Craig Ringer