首页 > 解决方案 > 获取逗号分隔的字符串中第一次出现的单词

问题描述

我在数据库中有一个名为 products 的特定字段,它将数据存储为逗号分隔。

我想要做的是检索整个字符串中第一次出现的单词,其中包含“IN”字符,然后获取“IN”之后的数字。

我尝试的是以下代码,但这将返回“15,12”。

products = "IN15,IN12"

products = "IN 15,IN12"

products = "TEST,IN15"

WHEN REGEXP_LIKE(products, '^IN') THEN regexp_replace(products, '[^0-9]', '')

在上述所有情况下,在 IN 之后有逗号或没有逗号的情况下,我希望输出为“15”。

标签: oracleplsql

解决方案


像这样的东西?

SQL> with test (products) as
  2    (select 'IN15,IN12'  from dual union all
  3     select 'IN 15,IN12' from dual union all
  4     select 'TEST,IN15'  from dual
  5    )
  6  select products,
  7    regexp_substr(substr(products, instr(products, 'IN') + 2), '\w+') result
  8  from test;

PRODUCTS   RESULT
---------- ----------------------------------------
IN15,IN12  15
IN 15,IN12 15
TEST,IN15  15

SQL>

它有什么作用:

  • INSTRIN在字符串中查找出现的
  • SUBSTR返回第一个之后的所有内容IN
  • REGEXP_SUBSTR提取该子字符串中的第一个单词

推荐阅读