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

前端 未结 14 889
挽巷
挽巷 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:11

    If you have Oracle 10g, REGEXP_REPLACE is pretty flexible.

    Using the following string as a test:

    chr(9) || 'Q   qwer' || chr(9) || chr(10) ||
    chr(13) || 'qwerqwer     qwerty' || chr(9) || 
    chr(10) || chr(13)
    

    The [[:space:]] will remove all whitespace, and the ([[:cntrl:]])|(^\t) regexp will remove non-printing characters and tabs.

    select
        tester,
        regexp_replace(tester, '(^[[:space:]]+)|([[:space:]]+$)',null)
                regexp_tester_1,
        regexp_replace(tester, '(^[[:cntrl:]^\t]+)|([[:cntrl:]^\t]+$)',null) 
                regexp_tester_2
    from
        (
        select
            chr(9) || 'Q   qwer' || chr(9) || chr(10) ||
                    chr(13) || 'qwerqwer     qwerty' || chr(9) || 
                    chr(10) || chr(13) tester 
        from 
            dual
        )
    

    Returning:

    • REGEXP_TESTER_1: "Qqwerqwerqwerqwerty"
    • REGEXP_TESTER_2: "Q qwerqwerqwer qwerty"

    Hope this is of some use.

    0 讨论(0)
  • 2021-01-30 11:12

    How about the quick and dirty translate function?

    This will remove all occurrences of each character in string1:

    SELECT translate(
               translate(
                   translate(string1, CHR(10), '')
               , CHR(13), '')
           , CHR(09), '') as massaged
    FROM BLAH;
    

    Regexp_replace is an option, but you may see a performance hit depending on how complex your expression is.

    0 讨论(0)
  • 2021-01-30 11:13

    If at all anyone is looking to convert data in 1 variable that lies in 2 or 3 different lines like below

    'Data1
    
    Data2'
    

    And you want to display data as 'Data1 Data2' then use below

    select TRANSLATE ('Data1
    
    Data2', ''||CHR(10), ' ') from dual;
    

    it took me hrs to get the right output. Thanks to me I just saved you 1 or 2 hrs :)

    0 讨论(0)
  • 2021-01-30 11:14

    For what version of Oracle? 10g+ supports regexes - see this thread on the OTN Discussion forum for how to use REGEXP_REPLACE to change non-printable characters into ''.

    0 讨论(0)
  • 2021-01-30 11:16

    Below code can be used to Remove New Line and Table Space in text column

    Select replace(replace(TEXT,char(10),''),char(13),'')
    
    0 讨论(0)
  • 2021-01-30 11:20

    This how I would implement it:

         REGEXP_REPLACE(text,'(^[[:space:]]*|[[:space:]]*$)')
    
    0 讨论(0)
提交回复
热议问题