Trim Whitespaces (New Line and Tab space) in a String in Oracle

前端 未结 14 891
挽巷
挽巷 2021-01-30 10:29

I need to trim New Line (Chr(13) and Chr(10) and Tab space from the beginning and end of a String) in an Oracle query. I learnt that there is no easy way to trim multiple charac

相关标签:
14条回答
  • 2021-01-30 11:20
    TRIM(BOTH chr(13)||chr(10)||' ' FROM str)
    
    0 讨论(0)
  • 2021-01-30 11:23

    You could use both LTRIM and RTRIM.

    select rtrim(ltrim('abcdab','ab'),'ab') from dual;
    

    If you want to trim CHR(13) only when it comes with a CHR(10) it gets more complicated. Firstly, translated the combined string to a single character. Then LTRIM/RTRIM that character, then replace the single character back to the combined string.

    select replace(rtrim(ltrim(replace('abccccabcccaab','ab','#'),'#'),'#'),'#','ab') from dual;
    
    0 讨论(0)
  • 2021-01-30 11:24

    Fowloing code remove newline from both side of string:

    select ltrim(rtrim('asbda'||CHR(10)||CHR(13) ,''||CHR(10)||CHR(13)),''||CHR(10)||CHR(13))  from dual
    

    but in most cases this one is just enought :

    select rtrim('asbda'||CHR(10)||CHR(13) ,''||CHR(10)||CHR(13)))  from dual
    
    0 讨论(0)
  • 2021-01-30 11:25

    Instead of using regexp_replace multiple time use (\s) as given below;

    SELECT regexp_replace('TEXT','(\s)','')
    FROM dual;
    
    0 讨论(0)
  • 2021-01-30 11:27

    I know this is not a strict answer for this question, but I've been working in several scenarios where you need to transform text data following these rules:

    1. No spaces or ctrl chars at the beginning of the string
    2. No spaces or ctrl chars at the end of the string
    3. Multiple ocurrencies of spaces or ctrl chars will be replaced to a single space

    Code below follow the rules detailed above:

    WITH test_view AS (
      SELECT CHR(9) || 'Q   qwer' || CHR(9) || CHR(10) ||
             CHR(13) || ' qwerqwer     qwerty  ' || CHR(9) || 
             CHR(10) || CHR(13) str
      FROM DUAL
    ) SELECT 
         str original
        ,TRIM(REGEXP_REPLACE(str, '([[:space:]]{2,}|[[:cntrl:]])', ' ')) fixed
      FROM test_view;
    
    
    ORIGINAL               FIXED                 
    ---------------------- ----------------------
        Q   qwer           Q qwer qwerqwer qwerty
    
     qwerqwer     qwerty                                         
    
    1 row selected.
    
    0 讨论(0)
  • 2021-01-30 11:36
    TRANSLATE (column_name, 'd'||CHR(10)||CHR(13), 'd')
    

    The 'd' is a dummy character, because translate does not work if the 3rd parameter is null.

    0 讨论(0)
提交回复
热议问题