Home > Net >  How to replace each character like something, except those that have a certain character just before
How to replace each character like something, except those that have a certain character just before

Time:03-25

I have a text like this

'
-line1 //no space between line1 and 2
-line2

-line4

-line6
'

I want the text to become like this ( add break line before '-' only if there empty line before)

'-line1 //now empty line between line1 and 2

-line2

-line4

-line6
'

I'm thinking about using REGEXP_REPLACE.

SELECT REGEXP_REPLACE (mytext, '-', chr(13) || '-')

This function add a line after every -. Is there an option to avoid replacing if there is an empty line before.

CodePudding user response:

It seems that oracle regex does not support look-ahead and look-backs.
We could do your replace and then eliminate anywhere that there are 2 concescutive empty lines. We look for sequences of three newlines \n = Chr(13) in a row, and replacing them with 2.

SELECT 
  REGEXP_REPLACE (
    REGEXP_REPLACE (
       mytext,'-', '\n-'),
    '\n\n\n','\n\n')

NB \n\n\n can also we written \n{3} .

CodePudding user response:

You could replace any newline which is preceded by a non-newline character and followed by a - with two newlines:

SELECT REGEXP_REPLACE('-line1
-line2

-line4

-line6', '[^' || chr(10) || ']' || chr(10) || '-', '1' || chr(10) || chr(10) || '-') AS out
FROM dual

Output:

-line1

-line2

-line4

-line6

Demo on dbfiddle

  • Related