regexoracle-databaseregexp-substrconnect-by

Use connect by by in REGEXP_SUBSTR without breaking result to multiple rows


SELECT CHR(91)||'a-zA-Z0-9._%-'||CHR(93)||'+'|| listagg(REGEXP_SUBSTR('aaa@yahoo.com, bbb@hotmail.com', '@'||CHR(91)||'^,'||CHR(93)||'+', 1, LEVEL), ', ') within group (order by level) as domain
FROM DUAL
CONNECT BY REGEXP_SUBSTR('aaa@yahoo.com, bbb@hotmail.com','@'||CHR(91)||'^,'||CHR(93)||'+', 1, LEVEL) IS NOT NULL
order by 1;

Above script only has the regular expression in front of @yahoo.com

 [a-zA-Z0-9._%-]+@yahoo.com, @hotmail.com

Expected result:

[a-zA-Z0-9._%-]+@yahoo.com, [a-zA-Z0-9._%-]+@hotmail.com

Solution

  • Sure; aggregate them back.

    SQL> SELECT listagg(REGEXP_SUBSTR('aaa@yahoo.com, bbb@hotmail.com', '@'||CHR(91)||'^,'||CHR(93)||'+', 1, LEVEL), ', ') within group (order by level) as domain
      2  FROM DUAL
      3  CONNECT BY REGEXP_SUBSTR('aaa@yahoo.com, bbb@hotmail.com','@'||CHR(91)||'^,'||CHR(93)||'+', 1, LEVEL) IS NOT NULL
      4  order by 1;
    
    DOMAIN
    ----------------------------------------------------------------------------------------------------
    @yahoo.com, @hotmail.com
    
    SQL>
    

    If you want to put the regexp prefix to all domains, then

    SQL>     SELECT LISTAGG (   '[a-zA-Z0-9._%-]+'
      2                      || REGEXP_SUBSTR ('aaa@yahoo.com, bbb@hotmail.com',
      3                                        '@' || CHR (91) || '^,' || CHR (93) || '+',
      4                                        1,
      5                                        LEVEL),
      6                      ', ')
      7             WITHIN GROUP (ORDER BY LEVEL) AS domain
      8        FROM DUAL
      9  CONNECT BY REGEXP_SUBSTR ('aaa@yahoo.com, bbb@hotmail.com',
     10                            '@' || CHR (91) || '^,' || CHR (93) || '+',
     11                            1,
     12                            LEVEL)
     13                IS NOT NULL;
    
    DOMAIN
    -----------------------------------------------------------------------------------------------
    [a-zA-Z0-9._%-]+@yahoo.com, [a-zA-Z0-9._%-]+@hotmail.com
    
    SQL>