在 sql 中使用正则表达式定义新变量

Using regex in sql to define new variable

如果可能,我需要使用 sql 和正则表达式从“旧”列派生“新”列。我正在使用 Oracle SQL Developer。 如果我在 R 或 Python 中使用正则表达式,我将使用此方法获取“新”列:

[1,2,3,4,5,6,7,8,9]{1,5}|\b0\b

old              new
P003             3 
4                4 
P00005           5
P0005            5
12               12
P00000016        16
0                0

谢谢。

使用这个:

REGEXP_SUBSTR(old, '[1-9]{1,9}0{0,10}|[1-9]{1,5}|\b0\b') as new

这是一种选择:

SQL> with test (old) as
  2    (select 'P003'      from dual union all
  3     select '4'         from dual union all
  4     select 'P00005'    from dual union all
  5     select 'P0005'     from dual union all
  6     select '12'        from dual union all
  7     select 'P00000016' from dual union all
  8     select '0'         from dual
  9    )
 10  select old, to_number(regexp_substr(old, '\d+')) new
 11  from test;

OLD              NEW
--------- ----------
P003               3
4                  4
P00005             5
P0005              5
12                12
P00000016         16
0                  0

7 rows selected.

SQL>