Search code examples
sqlregexoracle-databaseregexp-replaceregexp-like

RegExp Find and Replace ignoring part matches


I have a string formatted like:

'(val$1,val$1,val$1,val$2,val$3,val$4,val$5,val$6,val$7,val$8,val$9,val$10,val$11,val$12)'

and what I am trying to do is replace val$1 with some text e.g. XYZ

Matching on just val$1 produces:

'(XYZ,XYZ,XYZ,val$2,val$3,val$4,val$5,val$6,val$7,val$8,val$9,XYZ0,XYZ1,XYZ2)'

If anyone fancies giving me a hand, I would love to know what reg exp would ignore the ones at the end so the resulting string would look like:

'(XYZ,XYZ,XYZ,val$2,val$3,val$4,val$5,val$6,val$7,val$8,val$9,val$10,val$11,val$12)'

Solution

  • You can add an extra digit by \D to the pattern for regexp_replace

    select regexp_replace('(val$1,val$1,val$1,val$2,val$3,val$4,val$5,val$6,val$7,val$8,val$9,
                            val$10,val$11,val$12)','\val\$1(\D)','XYZ\1') as "Result"
      from dual;
    
    Result
    ----------------------------------------------------------------------------------
    (XYZ,XYZ,XYZ,val$2,val$3,val$4,val$5,val$6,val$7,val$8,val$9,val$10,val$11,val$12)