Oracle extract variable number from string

旧城冷巷雨未停 提交于 2019-12-08 08:37:11

问题


I'm looking to extract a specific number out of a string of mixed alphanumeric characters that are variable in length in a query. I will need this in order to calculate a range based off that number. I'm using Oracle.

Example:

D-3-J32P232

-I need to grab the J32 at least, and most likely even the 32 out of that string. This range of numbers can change at any given time.

It could range from:

D-3-J1P232 to D-3-J322P2342

The numbers after the second and third letters can be any number of length. Is there any way to do this?


回答1:


REGEXP_SUBSTR could work (11g version):

SELECT REGEXP_SUBSTR('D-3-J322P2342','([A-Z]+-\d+-[A-Z]+)(\d+)',1,1,'i',2) num
  FROM dual;

A test of your sample data:

SQL> SELECT REGEXP_SUBSTR('D-3-J322P2342',''([A-Z]+-\d+-[A-Z]+)(\d+)',1,1,'i',2) num
  2    FROM dual;

NUM
---
322

SQL>

This will accept any case alpha string, followed by a dash, followed by one or more digits, followed by a dash, followed by another any case alpha string, then your number of interest.

In 10g REGEXP_REPLACE, it's bit less straightforward, as they did not add the ability to reference subexpressions until 11g:

SELECT REGEXP_SUBSTR(str,'\d+',1,1) NUM
  FROM (SELECT REGEXP_REPLACE('D-3-J322P2342','([A-Z]+-\d+-[A-Z]+)','',1,1,'i') str
          FROM dual);

Your sample data:

SQL> SELECT REGEXP_SUBSTR(str,'\d+',1,1) NUM
  2    FROM 
       (SELECT REGEXP_REPLACE('D-3-J322P2342','([A-Z]+-\d+-[A-Z]+)','',1,1,'i') str
  3       FROM dual);

NUM
---
322



回答2:


This is simpler and gets both the numbers for the range

select  substr( REGEXP_SUBSTR('D-3-J322P2342','[A-Z][0-9]+',1,1),2),
             substr( REGEXP_SUBSTR('D-3-J322P2342','[A-Z][0-9]+',1,2),2)
from dual



回答3:


REGEXP_SUBSTR would do the job



来源:https://stackoverflow.com/questions/6514189/oracle-extract-variable-number-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!