在字符串之间加零

时间:2017-10-20 14:32:26

标签: sql oracle

我有三个场景。

情景1:

如果我有以下字符串

实际字符串:1111-2222-33

需要通过添加前导零来替换。

格式化字符串:01111-2222-33

情景2:

如果我有以下字符串

实际字符串:11111-222-33

需要更换,例如在第一个' - '

开始之前添加零

格式化字符串:11111-0222-33

场景3:

如果我有以下字符串

实际字符串:11111-2222-3

需要在第二个'-'

开始之前添加零来替换

格式化字符串:11111-2222-03

如何转换上述字符串?在此先感谢

2 个答案:

答案 0 :(得分:0)

这是一种方法。它使用标准字符串函数,如果性能是一个问题,这可能很重要(标准函数比正则表达式函数快得多)。

但请注意,这也会将字符串'do-it-yourself'转换为'000do-00it-yo'。如果不需要,您必须在原始帖子中解释所有规则。

with
  inputs ( str ) as (
    select '1111-2222-33' from dual union all
    select '11111-222-33' from dual union all
    select '11111-2222-3' from dual union all
    select '1234-03-0'    from dual
  )
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins BELOW THIS LINE. Use your actual table and column names.
select str, 
       lpad(substr(str, 1, instr(str, '-') - 1), 5, '0') || '-' ||
       lpad(substr(str, instr(str, '-') + 1, 
                        instr(str, '-', 1, 2) - instr(str, '-') - 1), 4, '0')
       || '-' || lpad(substr(str, instr(str, '-', 1, 2) + 1), 2, '0') as new_str
from   inputs
;

STR          NEW_STR     
------------ -------------
1111-2222-33 01111-2222-33
11111-222-33 11111-0222-33
11111-2222-3 11111-2222-03
1234-03-0    01234-0003-00

答案 1 :(得分:0)

为了论证,这是使用正则表达式的另一种方法。对于第一个元素,选择第一个出现的最多5个数字后面跟一个破折号,然后选择lpad,用零到5个长度。

with tbl(str) as (
  select '1111-2222-33' from dual union all
  select '11111-222-33' from dual union all
  select '11111-2222-3' from dual union all
  select '1234-03-0'    from dual
)
select 
  lpad(regexp_substr(str, '(\d{0,5})-', 1, 1, NULL, 1), 5, '0') || '-' ||
  lpad(regexp_substr(str, '(\d{0,4})-', 1, 2, NULL, 1), 4, '0') || '-' ||
  lpad(regexp_substr(str, '-(\d{0,2})$', 1, 1, NULL, 1), 2, '0') formatted 
from tbl;