2015-06-19 50 views
0

to_char適用於下面的單個匹配時工作正常。Oracle SQL:如何使用to_char轉換字符串中的子字符串

select to_char('54523234', '99,999,999,999') 

我使用正則表達式來查找只匹配字符串中的貨幣。但是,當我申請TO_CHAR第一組,這是行不通的

SELECT regexp_replace ('24444.88, 54523234.78, and 1044.52 are numbers in this example.', 
'(([0-9]+){1,10})+\.([0-9]{2})', to_char('\1'.'99,999,999,999')) 
FROM dual; 

我要顯示等的輸出字符串: 24,444.8854,523,234.781,044.52在這個例子中的數字。

回答

1

在這裏你去哥哥,這是一個有趣的:

SELECT regexp_replace(regexp_replace ('234234234.88, 24444.88, 54523234.78, and 1044.52 are numbers in this example.', 
'(([0-9]{3})\.)', 
',\1'),'(([0-9]{3}),)',',\1') 
FROM dual 
+0

謝謝兄弟!這是完美的答案。簡單而偉大! – Anandh

+0

沒問題,我喜歡解決它:) –

0

SQL Fiddle

的Oracle 11g R2架構設置

CREATE OR REPLACE FUNCTION reverseString(
    str VARCHAR2 
) RETURN VARCHAR2 
AS 
    v_str VARCHAR2(4000); 
BEGIN 
    FOR i IN REVERSE 1 .. LENGTH(str) LOOP 
    v_str := v_str || SUBSTR(str, i, 1); 
    END LOOP; 
    RETURN v_str; 
END; 
/

CREATE OR REPLACE FUNCTION insertDecimalSeparators(
    str VARCHAR2 
) RETURN VARCHAR2 
AS 
    v_str VARCHAR2(4000) := str; 
    v_pos NUMBER(4,0); 
    v_num VARCHAR2(4000); 
    v_rpl VARCHAR2(4000); 
    c_re CONSTANT CHAR(9) := '\d+\.?\d*'; 
BEGIN 
    FOR i IN REVERSE 1 .. REGEXP_COUNT(str, c_re) LOOP 
    v_pos := REGEXP_INSTR(str, c_re, 1, i); 
    v_num := REGEXP_SUBSTR(str, c_re, 1, i); 
    v_rpl := REGEXP_REPLACE(
       reverseString(v_num), 
       '((\d*\.)?\d{3})', 
       '\1,', 
       1, 
       0 
      ); 
    IF SUBSTR(v_rpl, -1) = ',' THEN 
     v_rpl := SUBSTR(v_rpl, 1, LENGTH(v_rpl) - 1); 
    END IF; 
    v_str := SUBSTR(v_str, 1, v_pos - 1) || reverseString(v_rpl) || SUBSTR(v_str, v_pos + LENGTH(v_num)); 
    END LOOP; 
    RETURN v_str; 
END; 
/

查詢1

WITH data (str) AS (
      SELECT '244445.88, 54523234.78, and 1044.12345678 are numbers.' FROM DUAL 
    UNION ALL SELECT 'abc123456' FROM DUAL 
    UNION ALL SELECT '123, 12, 1234, 123.1' FROM DUAL 
    UNION ALL SELECT '123.' FROM DUAL 
) 
SELECT str, 
     insertDecimalSeparators(str) AS commaSep 
FROM data 

Results

|             STR |             COMMASEP | 
|--------------------------------------------------------|------------------------------------------------------------| 
| 244445.88, 54523234.78, and 1044.12345678 are numbers. | 244,445.88, 54,523,234.78, and 1,044.12345678 are numbers. | 
|            abc123456 |             abc123,456 | 
|         123, 12, 1234, 123.1 |          123, 12, 1,234, 123.1 | 
|           123.|            123.| 
相關問題