5

Given a string I want to extract all expression matching a regexp (e.g. email) as an array. Here is my actual code, using PostgreSQL 9.4 :

select regexp_matches('[email protected] lorem ipsum [email protected]',
                      '([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4})',
                      'g')

The output is 2 records:

 regexp_matches  
 -----------------
 {[email protected]}
 {[email protected]}
 (2 rows)

What I want is to have all the matches in one array e.g.:

regexp_matches  
-----------------
{[email protected], [email protected]}
(1 row)

How to achieve that?

1 Answer 1

6

You can unnest each result array, then array_agg the lot of them together.

It's a bit ugly:

select array_agg(x)
from (
    select unnest(
       regexp_matches('[email protected] lorem ipsum [email protected]',
                      '([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4})',
                      'g')
    )
) a(x);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer @CraigRinger, I will use your suggestion and create a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.