1

I know to select all matched occurrences by a regular expression to one column in multiple rows as below:

SELECT REGEXP_SUBSTR(str, '\+?\d{3,11}', 1, LEVEL) AS substr
FROM (
    SELECT 'Txa233141b Ta233141 Ta233142 Ta233147 Ta233148' AS str FROM DUAL
)
CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(str, '[^ ]+')) + 1;

the result is

233141
233141
233142
233147
233148

But I want to the result as below, what can I do?

233141,233141,233142,233147,233148

2 Answers 2

2

Use simple string functions rather than trying to split the string and the aggregate it:

Query:

WITH test_data ( str ) AS (
  SELECT 'Txa233141b Ta233141 Ta233142 Ta233147 Ta233148' AS str FROM DUAL
)
SELECT TRIM(
         TRAILING ',' FROM
         REGEXP_REPLACE(
           str,
           '.*?(\+?\d{3,11}|$)',
           '\1,'
         )
       ) AS replaced_str
FROM   test_data

Output:

| REPLACED_STR                       |
| :--------------------------------- |
| 233141,233141,233142,233147,233148 |

db<>fiddle here

Sign up to request clarification or add additional context in comments.

Comments

1

You can also use listagg on top of your query as following:

SELECT listagg(REGEXP_SUBSTR(str, '\+?\d{3,11}', 1, LEVEL),',') within group (order by 1) AS substr
FROM (
    SELECT 'Txa233141b Ta233141 Ta233142 Ta233147 Ta233148' AS str FROM DUAL
)
CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(str, '[^ ]+')) + 1;

Cheers!!

3 Comments

Hi, the result is 233141233141233142233147233148, that is not what I need:)
Set LISTAGG's second parameter to a comma, e.g. listagg(regexp_substr(blabla), ', ') within group ...
Correct @littlefoot

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.