CREATE OR REPLACE FUNCTION APLICA_MASCARA(
        P_VALORCAMPO IN VARCHAR2,
        P_VALORMASCARA IN VARCHAR2) RETURN VARCHAR2
AS
   V_MASCARAORACLE VARCHAR2(150);
   V_PARAMSTOSET VARCHAR2(50);
   V_QTDIGITO NUMBER;
   V_POINTER NUMBER;
BEGIN
   V_POINTER := 0;
   V_QTDIGITO := LENGTH(P_VALORCAMPO);
   FOR C_NIVEIS IN (SELECT LENGTH(REGEXP_SUBSTR(P_VALORMASCARA,'[^./-]+', 1, LEVEL)) VALORLENGTH, REGEXP_SUBSTR(P_VALORMASCARA,'[./-]+', 1, LEVEL) SEPARADOR, ROWNUM FROM dual
                    CONNECT BY REGEXP_SUBSTR(P_VALORMASCARA, '[^./-]+', 1, LEVEL) IS NOT NULL)
   LOOP
      V_POINTER := V_POINTER+C_NIVEIS.VALORLENGTH;
      --DBMS_OUTPUT.PUT_LINE('ROWNUM: '||C_NIVEIS.ROWNUM||' V_POINTER: '||V_POINTER||' V_QTDIGITO: '||V_QTDIGITO); 
      IF V_POINTER >= V_QTDIGITO THEN
         GOTO END_LOOP;
      END IF;
      V_MASCARAORACLE := V_MASCARAORACLE||'(.{'||C_NIVEIS.VALORLENGTH||'})';
      V_PARAMSTOSET := V_PARAMSTOSET||'\'||C_NIVEIS.ROWNUM||C_NIVEIS.SEPARADOR;   
   END LOOP;
   
   <<END_LOOP>>
   NULL; -- evitar erro de GOTO
   RETURN REGEXP_REPLACE(P_VALORCAMPO, V_MASCARAORACLE, V_PARAMSTOSET, 1, 1);
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('APLICA_MASCARA','6.49.014'); END;
/
