Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

regexp_matches, array per row

In PostgreSQL, I have a table as follow.

|    id    |     mycolumn   |
| -------- | -------------- |
| 1        | /1/2/8/        |
| 2        | /1/40/22/11/   |
| 3        | /1/15/35/      |

I am trying to get all the numbers, for each row, in an array.
So far I came up with the following:

    SELECT array_agg(matchx)
    FROM (
        SELECT unnest(regexp_matches(mycolumn,
                                     '[0-9]+',
                                     'g')) matchx
        FROM mytable
    ) x

What I want:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

|  array_agg   |
| ------------ |
| {1,2,8}      |
| {1,40,22,11} |
| {1,15,35}    |

What I get:

|        array_agg              |
| ----------------------------- |
| {1,2,8,1,40,22,11,1,15,35}    |

How is it possible to get an array per row?

>Solution :

No need for unnesting, just turn it into an array directly:

select id, string_to_array(trim(both '/' from mycolumn), '/')
from mytable;

The trim() is necessary, because otherwise you’d have empty elements in the array.


Your original approach would work if you group while aggregating back:

SELECT id, array_agg(matchx)
FROM (
    SELECT id, 
           unnest(regexp_matches(mycolumn,'[0-9]+','g')) matchx
    FROM mytable
) x
group by id;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading