Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve results from regexp_matches as one row

So, if have this string aassdd

This code:

regexp_matches('aassdd', 'a', 'g')

returns 2 different rows.

It is possible to retrieve all matches as one row? for example as array type as one row, that is from code above, needed result is: {a,a}

like image 822
Oto Shavadze Avatar asked May 17 '13 12:05

Oto Shavadze


3 Answers

The fact that regexp_matches() returns a set rather than a scalar is understandable but still somewhat annoying.

The only workaround I found is this somewhat ugly query:

select array_agg(i)
from (
   select (regexp_matches('aassdd', 'a', 'g'))[1] i 
)  t
like image 113
a_horse_with_no_name Avatar answered Nov 20 '22 19:11

a_horse_with_no_name


SELECT ARRAY(select array_to_string(regexp_matches('aassdd', 'a', 'g'),''));
like image 36
Muhammad Usama Avatar answered Nov 20 '22 19:11

Muhammad Usama


If regexp_matches() takes as parameter a column of an indexed table, there is one more way:

SELECT rid, array_agg(number) 
FROM 
    (SELECT 
       rid, 
       (regexp_matches(column,'[0-9]+','g'))[1] as number 
    FROM table) t
GROUP BY rid
like image 2
RusArt Avatar answered Nov 20 '22 20:11

RusArt