从字符串中提取数字-自定义

时间:2019-08-23 12:47:19

标签: regex oracle oracle-sqldeveloper

我想从字符串中提取“大多数”数字,并在末尾添加“ JW”。 我的值如下:

RFID_DP_IDS339020JW3_IDMsg - Result = 339020JW
RFID_DP_IDSA72130JW_IDMsg --> 72130JW
RFID_DP_IDS337310JW1_IDMsg --> 337310JW

基本上,我会删除所有首字母,保留所有数字和JW

现在我有这个

regexp_replace(Business_CONTEXT, '[^0-9]', '')||'JW' RegistrationPoint

但这将包括'JW'之后的数字

有什么主意吗?

2 个答案:

答案 0 :(得分:1)

怎么样?

  • result将在数字串后精确返回两个字母
  • result2将返回数字+ JW

选择最合适的那个。

SQL> with test (col) as
  2    (select 'RFID_DP_IDS339020JW3_IDMsg' from dual union all
  3     select 'RFID_DP_IDSA72130JW_IDMsg'  from dual union all
  4     select 'RFID_DP_IDS337310JW1_IDMsg' from dual
  5    )
  6  select col,
  7    regexp_substr(col, '\d+[[:alpha:]]{2}') result,
  8    regexp_substr(col, '\d+JW') result2
  9  from test;

COL                        RESULT                     RESULT2
-------------------------- -------------------------- --------------------------
RFID_DP_IDS339020JW3_IDMsg 339020JW                   339020JW
RFID_DP_IDSA72130JW_IDMsg  72130JW                    72130JW
RFID_DP_IDS337310JW1_IDMsg 337310JW                   337310JW

SQL>

答案 1 :(得分:0)

如果您确实要从给定的字符串中提取最长的数字字符串,则可以使用以下命令:

  WITH test (Business_CONTEXT) AS 
    (SELECT 'RFID_DP_IDS339020JW3_I9DMsg' from dual union all
     SELECT 'RFID_DP_IDSA72130JW_IDMsg'  from dual union all
     SELECT 'RFID_DP_IDS337310JW1_IDMsg' from dual
    )
  SELECT Business_CONTEXT
       , (SELECT MAX(regexp_substr(Business_CONTEXT, '\d+', 1, LEVEL)) 
                 KEEP (dense_rank last ORDER BY LENGTH(regexp_substr(Business_CONTEXT, '\d+', 1, LEVEL)))
            FROM dual
            CONNECT BY regexp_substr(Business_CONTEXT, '\d+', 1, LEVEL) IS NOT NULL) num
    FROM test

结果:

Business_CONTEXT            | NUM
----------------------------+-----
RFID_DP_IDS339020JW3_I9DMsg | 339020
RFID_DP_IDSA72130JW_IDMsg   |  72130
RFID_DP_IDS337310JW1_IDMsg  | 337310