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?
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.
Using the String#split Method<=\\G. {” + n + “}) where n is the number of characters.
In Python, we have an in-built method called list() to split the strings into a sequence of 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With