Skip to content
Advertisement

Replace characters with padding zeros

I have a table with values:

100-1234-5
100-0004567-00
300-122334556-87

and I need to replace the first dash (-) with zeros, so that the total length is exactly 18 characters, and insert it back into the database:

1000000000000123-45
1000000000004567-00
3000000122334556-87

If that is not possible, then maybe do the same using grep

Advertisement

Answer

I need to replace the first dash (-) with zeros, so that the total length is exactly 18

You can deconstruct the string and then put it back together:

select (regexp_substr(str, '[^-]+', 1, 1) || 
        rpad('0', 19 - length(str), '0') ||
        regexp_substr(str, '[^-]+', 1, 2) || '-' ||
        regexp_substr(str, '[^-]+', 1, 3)
       )
from t;

Note that this returns the results that you describe, not the results given in the question — I assume you have a typo there.

Here is a db<>fiddle

This is easily incorporated into an update:

update t
    set str = (regexp_substr(str, '[^-]+', 1, 1) || 
               rpad('0', 19 - length(str), '0') ||
               regexp_substr(str, '[^-]+', 1, 2) || '-' ||
               regexp_substr(str, '[^-]+', 1, 3)
              );
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement