Search code examples
regexoracle-databaseoracle11gdbms-output

adding a space after each 4th number/digit Oracle 11G


I am trying to get a space into every 4th number/digit (not character). This is what I come up with:

  newStudentNumber := regexp_replace(newStudentNumber, '[[:digit:]](....)', '\1 ');
  dbms_output.put_line(newStudentNumber);

result:

NL 2345 7894  TUE

What I actually want:

NL 1234 5678 944 TUE

My code replaces the number at every 4th place with a spacebar, instead of adding a space like the wanted result above.

Can anyone explain this to me?

Thanks in advance


Solution

  • You can use the following regex..

    ([[:digit:]]{4})
    

    And replace with what you are doing now.. \1(space)

    Why yours is not working?

    Your regex matches a digit and captures next 4 characters (not only digits). So.. when you do a replace.. the digit which is matched but not captured is also replaced.. and not because it is unable to insert.

    Explanation for input = NL 12345678944 TUE and regex = [[:digit:]](....):

    NL 12345678944 TUE   (it will match digit "1" and captures "2345")
    

    See DEMO